Friday 14 December 2012

failure adding assembly to the cache

I have built a .net class library project, and signed assembly as well. I added assembly into gac and it went in fine.

When I copied assembly to a different machine and tried registering the dll I got following error

"Failure adding assembly to the cache: The module was expected to contain an assembly manifest"

The reason was the location I copied my dll from source was to grove and then tried coping directly from grove to remote machine, and this sometimes damage file data.

Resolution: Copy file and make sure file copied from source to destination is correctly copied. In my particular case I copied it from groove to local machine first and then copied from local machine to vm.

Wednesday 12 December 2012

ssrs to pdf and other docs from crm 2011

http://a33ik.blogspot.co.uk/2012/11/general-approaches-to-generation-of.html

Tuesday 11 December 2012

Could not load assembly

I have created a class library project, and build assembly using .net 4.0, i created a console app to test my dll and it was working fine, when i registered it into GAC and in CRM plugin where I reference this assembly. when plugin was triggering I got error saying could not load assembly,

when looking into GAC assembly was there

Tried using fuslogvw to find where the problem is but no luck
Tried using dotpeek but no luck

Spent so much time in investigating why its working fine from console app but not from CRM plugin though I can see from gacutil -l "assembly name" that assembly is there.

Resolution:
Project was built using x86, and CRM app pool runs under 64 bit, so by changing build type of class library to any cpu everything is fine now.

Thursday 6 December 2012

Report Server error message about insufficient permissions

When I try to browse report server http://<serverurl>/reportserver I got following error


The permissions granted to user 'domain\username' are insufficient for performing this operation. (rsAccessDenied)



Resolution:
Open the browser with for a different user who has access to reportserver e.g. administrator

1. Go to http://<serverurl>/reports

2. Click on "Folder Settings" option

3. Click on Security Tab

4. Click on New Role Assignment

5. Enter
   Group or User name: <domain\username>
   Select role you like this user to have (e.g. publisher,browser)





Wednesday 5 December 2012

CRM notification

http://blogs.msdn.com/b/johnsullivan/archive/2011/11/02/crm-2011-custom-form-notification.aspx

Monday 3 December 2012

Microsoft Dynamics CRM List component is not installed

List component is installed on SharePoint, however user is still getting following error.


Resolution: Make sure the current user has sufficient rights on SharePoint site, in my dev environment I gave user Site Collection Administrator, this is a dev environment and giving this role was safe, but on prod or system test relevant security privileges should be given to user.

Friday 30 November 2012

add methods to string class


String.prototype.format = function () {
    var formatted = this;
    for (var i = 0; i < arguments.length; i++) {
        var regexp = new RegExp('\\{' + i + '\\}', 'gi');
        formatted = formatted.replace(regexp, arguments[i]);
    }
    return formatted;
};

String.prototype.rtrim = function () {
    return this.replace(/\s+$/, "");
}


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

if (typeof (prefix.namespace1) == "undefined") {
    prefix.namespace1 = {};
}

//This will establish a more unique namespace for functions in this library. This will reduce the
// potential for functions to be overwritten due to a duplicate name when the library is loaded.
prefix.namespace1.namespace2 = {

      someFunction: function{
var temp1 = "this is a test string {0}";

temp1.format("hello");

   },
namespace

};

http://www.somacon.com/p355.php

Wednesday 21 November 2012

Navigate form


var navigateFormId;

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

t1.Entity = {

    Form:
{
    Default: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx",
    OtherForm: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx"
},
    FormType:
{
    Undefined: 0,
    Create: 1,
    Update: 2,
    ReadOnly: 3,
    Disabled: 4,
    QuickCreate: 5,
    BulkEdit: 6
},

    OnLoad: function () {

        var formType = Xrm.Page.ui.getFormType();

        try {

            if (formType == t1.Entity.FormType.Update) {

                var lookup= Xrm.Page.getAttribute("new_attribute").getValue();

                var currentFormId = Xrm.Page.ui.formSelector.getCurrentItem().getId();

                if (lookup && currentFormId.toLowerCase() != t1.Entity.Form..toLowerCase()) {
                   
                    navigateFormId = E2.BaseContract.Form.OtherForm.toLocaleLowerCase();

                } else {

                    if (currentFormId.toLowerCase() != t1.Entity.Form.Default.toLowerCase()) {

                        navigateFormId = t1.Entity.Form.Default.toLocaleLowerCase();
                    }

                }
            }

            if (navigateFormId) {               

                setTimeout("t1.Entity.Navigate()", 4000);

            }

        } catch (e) {

        }
    },
    Navigate: function () {

        if (navigateFormId) {

            Xrm.Page.ui.formSelector.items.get(navigateFormId).navigate();

        }
    },
    __namespace: true
};

Monday 19 November 2012

The key specified to compute a hash value is expired


The key specified to compute a hash value is expired, only active keys are valid. Expired Key : CrmKey(Id:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, ScaleGroupId:00000000-0000-0000-0000-000000000000, KeyType:CrmWRPCTokenKey, Expired:True, ValidOn:10/17/2012 08:18:40, ExpiresOn:11/19/2012 08:18:40, CreatedOn:10/17/2012 08:18:40, CreatedBy:NT AUTHORITY\NETWORK SERVICE.

Resolution: start Microsoft dynamic Async Service and Micorosoft dynamic async maintinance service

Friday 16 November 2012

Document navigation link not visible for some users

In CRM I got Business units e.g. Child business Unit A and Child business unit B, I am using SharePoint integration. I have got two custom entities e.g. custom Entity A and custom Entity B. Custom entity A has an organisation level access to every privilege  however custom entity B has Business Unit level access to every privilege. I have got User A assigned to Child business Unit A, and User B assigned to child business unit B, both have been given security roles defined above.
SharePoint is set-up to have every CRM user has access to SharePoint site.

When user A creates custom Entity A and custom Entity B record he creates SharePoint documents for both records, and assigns record for custom Entity B to User B. 

User B is able to see document link on custom Entity A, however not on custom Entity B. This is due to custom Entity A has organisation level access. however on custom entity B user has got business unit access, though User B was able to see/access SharePoint location by coping relevant record's SharePoint location URL to his browser.

Resolution:

After doing bit of research/investigation I found that by giving user "ISV Extension" privilege present at customisation tab in security role. user B can also see document link for record of custom entity B.

Most likely this is happening due to "ISV Extension" are created and maintained in the system for business unit level and by Assigning custom entity record B to user relevant isv extension records are not re-assigned. and by setting "ISV Extension" user has got read access to all "ISV Extension" records in the system.

Tuesday 13 November 2012

Assembly failed to load 0x80131515

We have a custom activity which loads assembly using reflection, this is working fine however when we copied assembly to system test it started failing over with following error.

Unhandled Exception: Microsoft.Xrm.Sdk.InvalidPluginExecutionException: An error occurred in the XYZ plug-in.
   at name.customactivity.Execute(CodeActivityContext executionContext)
   at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
   at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)
Inner Exception: System.IO.FileLoadException: Could not load file or assembly 'file:///C:\Program Files\Microsoft Dynamics CRM\Server\bin\assembly\anotherassembly.dll' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)
   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)
   at System.Reflection.Assembly.LoadFrom(String assemblyFile)
   at E2.Crm.SharePoint.Interfaces.EntitySpIntegrationFactory`1.FetchInstance(Entity entity)
   at E2.Lbh.Crm.SharePointIntegration.InitialiseSPDocStore.Execute(CodeActivityContext executionContext)
Inner Exception: System.NotSupportedException: An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See http://go.microsoft.com/fwlink/?LinkId=155569 for more information


Resolution: When assembly was copied it had a protected check box enabled, which was causing issues to not load propertly. Right click on assembly and go to properties and un-check protected option.
(This option sometime gets enabled automatically when copied across network)

Monday 12 November 2012

Send Email error


I have a custom entity A that has one to many releation with custom entity B, Custom entity A record and Custom Entity B records are in inactive state, When user clicks on custom ribbon button in javascript I change state of custom entity A and updates a datetime attribute e.g. activated childs on. which triggers a plugin which is running under service account, in the plugin I have logic to ignore which Custom entity B records to activate, as I am using solutions concept, this logic is on top level component, to pass these values I used shared variable and passed it list of guids of custom entity B to ignore.

on custom entity a, when plugin trigger it looks for shared variable and ignores the custom entity b records which are mentioned and then activates rest of the records.

on activate of custom entity b, i have another plugin which sends email.

and I was getting this error in this case. when whole above scenario is executed. when I simple use activate OOB button email sent is fine, but not when whole custom process is executed.

The whole above process works fine in my dev env but when deployed into system test I got following error.

The Web Service plug-in failed in OrganizationId: xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx; SdkMessageProcessingStepId: xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx; EntityName: email; Stage: 30; MessageName: Send; AssemblyName: Microsoft.Crm.Extensibility.InternalOperationPlugin, Microsoft.Crm.ObjectModel, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35; ClassName: Microsoft.Crm.Extensibility.InternalOperationPlugin; Exception: Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
   at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Web.Services.Protocols.LogicalMethodInfo.Invoke(Object target, Object[] values)
   at Microsoft.Crm.Extensibility.InternalOperationPlugin.Execute(IServiceProvider serviceProvider)
   at Microsoft.Crm.Extensibility.V5PluginProxyStep.ExecuteInternal(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
Inner Exception: System.Runtime.Serialization.SerializationException: Type 'System.Collections.Generic.List`1[[System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' with data contract name 'ArrayOfguid:http://schemas.microsoft.com/2003/10/Serialization/Arrays' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, Boolean verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiType(XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at WriteKeyValuePairOfstringanyTypeToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , ClassDataContract )
   at System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at WriteParameterCollectionToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , CollectionDataContract )
   at System.Runtime.Serialization.CollectionDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at WriteAsyncOperationDataToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , ClassDataContract )
   at System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at WriteAsyncOperationDataToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , ClassDataContract )
   at System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at WriteAsyncOperationDataToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , ClassDataContract )
   at System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
   at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
   at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
   at System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph)
   at Microsoft.Crm.Extensibility.AsynchronousStep.SerializeAsyncData(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.AsynchronousStep.Execute(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.SystemUserProxy.Execute(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.Pipeline.Execute(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.MessageProcessor.Execute(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.InternalMessageDispatcher.Execute(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.ExtensiblePlatformMessageDispatcher.Execute(PipelineExecutionContext pluginContext)
   at Microsoft.Crm.Extensibility.ExtensiblePlatformMessageDispatcher.UpdateWithInvocationSource(BusinessEntity entity, FilterExpression filter, Int32 invocationSource, ExecutionContext context)
   at Microsoft.Crm.Extensibility.ExtensiblePlatformMessageDispatcher.Update(BusinessEntity entity, FilterExpression filter, ExecutionContext context)
   at Microsoft.Crm.BusinessEntities.BusinessProcessObject.UpdateWithPipelineAndExtensions(IBusinessEntity entity, ExecutionContext context)
   at Microsoft.Crm.ObjectModel.GenericActivityServiceBase.UpdateInternal(IBusinessEntity entityInterface, ExecutionContext context)
   at Microsoft.Crm.ObjectModel.CommunicationActivityServiceBase.Update(IBusinessEntity entityInterface, ExecutionContext context)
   at Microsoft.Crm.ObjectModel.EmailService.UpdateHelper(IBusinessEntity entityInterface, ExecutionContext context, Boolean internalUpdateCall)
   at Microsoft.Crm.ObjectModel.EmailService.Send(Guid emailId, Boolean issueSend, String trackingToken, ExecutionContext context)

Resolution: Changed the Generic Collection from List<Guid> to array of []Guid, solution seems simple but it took me more than a day to track down and figure out that this was causing problem.


Sunday 11 November 2012

Error when calling sendEmail


I have registered a plugin on Entity A of SetStateDynamicEntity, and in this plugin I send email and in code I use calling user as the initiating user.

I have got another plugin which sets the state of Entity A, In this plugin I have correct initiating user, however this in SetStateDyamicEntity when I try to send email, initiating user is changed to SystemUser, and hence when email is sent following email error is thrown. as "System" User account does not have email address hence no approved user to send email.

The Web Service plug-in failed in OrganizationId: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx; SdkMessageProcessingStepId: 05cdbb1b-ea3e-db11-86a7-000a3a5473e8; EntityName: email; Stage: 30; MessageName: Send; AssemblyName: Microsoft.Crm.Extensibility.InternalOperationPlugin, Microsoft.Crm.ObjectModel, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35; ClassName: Microsoft.Crm.Extensibility.InternalOperationPlugin; Exception: Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
   at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Web.Services.Protocols.LogicalMethodInfo.Invoke(Object target, Object[] values)
   at Microsoft.Crm.Extensibility.InternalOperationPlugin.Execute(IServiceProvider serviceProvider)
   at Microsoft.Crm.Extensibility.V5PluginProxyStep.ExecuteInternal(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
Inner Exception: System.Runtime.Serialization.SerializationException: Type 'System.Collections.Generic.List`1[[System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' with data contract name 'ArrayOfguid:http://schemas.microsoft.com/2003/10/Serialization/Arrays' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, Boolean verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiType(XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at WriteKeyValuePairOfstringanyTypeToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , ClassDataContract )
   at System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at WriteParameterCollectionToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , CollectionDataContract )
   at System.Runtime.Serialization.CollectionDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at WriteAsyncOperationDataToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , ClassDataContract )
   at System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at WriteAsyncOperationDataToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , ClassDataContract )
   at System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerializeReference(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
   at WriteAsyncOperationDataToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , ClassDataContract )
   at System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
   at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
   at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
   at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
   at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
   at System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph)
   at Microsoft.Crm.Extensibility.AsynchronousStep.SerializeAsyncData(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.AsynchronousStep.Execute(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.SystemUserProxy.Execute(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.Pipeline.Execute(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.MessageProcessor.Execute(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.InternalMessageDispatcher.Execute(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.ExtensiblePlatformMessageDispatcher.Execute(PipelineExecutionContext pluginContext)
   at Microsoft.Crm.Extensibility.ExtensiblePlatformMessageDispatcher.UpdateWithInvocationSource(BusinessEntity entity, FilterExpression filter, Int32 invocationSource, ExecutionContext context)
   at Microsoft.Crm.Extensibility.ExtensiblePlatformMessageDispatcher.Update(BusinessEntity entity, FilterExpression filter, ExecutionContext context)
   at Microsoft.Crm.BusinessEntities.BusinessProcessObject.UpdateWithPipelineAndExtensions(IBusinessEntity entity, ExecutionContext context)
   at Microsoft.Crm.ObjectModel.GenericActivityServiceBase.UpdateInternal(IBusinessEntity entityInterface, ExecutionContext context)
   at Microsoft.Crm.ObjectModel.CommunicationActivityServiceBase.Update(IBusinessEntity entityInterface, ExecutionContext context)
   at Microsoft.Crm.ObjectModel.EmailService.UpdateHelper(IBusinessEntity entityInterface, ExecutionContext context, Boolean internalUpdateCall)
   at Microsoft.Crm.ObjectModel.EmailService.Send(Guid emailId, Boolean issueSend, String trackingToken, ExecutionContext context)


Resolution: In the plugin due to which SetStateDynamicEntity plugin is firing, use sharedvariable, and set the intiating user in shared variable and in SetStateDynamicEntity get the actual initiating user from SharedVairable, and use it as calling user.

Tuesday 30 October 2012

Change base currency

There is no supported way to change base currency. This is specified while creating organisational. However to change default currency Go to option and then on General tab, specify currency in "select a default currency option".

Friday 19 October 2012

Optionset

OptionSet

get intial value of option set, when form was opened

attributeobj.getInitialValue()



Dependent Optionset

http://msdn.microsoft.com/en-us/library/gg594433.aspx

Friday 12 October 2012

hide navigation links in crm 2011 using javascript


I had a requirement to control visibility of navigation link on some condition. I added onload function and from that function called following function.

function SetDocumentationVisbitlity(navigationlabel, visibility) { 

         var items = Xrm.Page.ui.navigation.items.get();
         for (var i in items) {
               var item = items[i];
               if (item.getLabel() == navigationLabel) {
                   item.setVisible(visibility);
               }
         }
}

Tuesday 9 October 2012

CRM Contracts

Introduction to Contract Management in Dynamics CRM 2011
http://magnetism.co.nz/blog/simon/simon-phillipss-blog/2011/04/25/Introduction_to_Contract_Management_in_Dynamics_CRM_2011.aspx

Dynamics CRM 2011 Contract Life Cycle
http://magnetism.co.nz/blog/simon/simon-phillipss-blog/2011/05/02/Dynamics_CRM_2011_Contract_Life_Cycle.aspx

Creating Contract Lines in Dynamics CRM 2011
http://magnetism.co.nz/blog/simon/simon-phillipss-blog/2011/05/14/Creating_Contract_Lines_in_Dynamics_CRM_2011.aspx

Dynamics CRM 2011 Creating a Contract Template
http://magnetism.co.nz/blog/simon/simon-phillipss-blog/2011/05/17/Dynamics_CRM_2011_Creating_a_Contract_Template.aspx

Creating a New Contract in Microsoft Dynamics CRM 2011
http://magnetism.co.nz/blog/simon/simon-phillipss-blog/2011/05/19/Creating_a_New_Contract_in_Microsoft_Dynamics_CRM_2011.aspx

Creating a contract in Microsoft Dynamics CRM 2011 part 2
http://magnetism.co.nz/blog/simon/simon-phillipss-blog/2011/05/21/Creating_a_contract_in_Microsoft_Dynamics_CRM_2011_part_2.aspx

Renewing Contracts in Microsoft Dynamics CRM 2011
http://magnetism.co.nz/blog/simon/simon-phillipss-blog/2011/05/24/Renewing_Contracts_in_Microsoft_Dynamics_CRM_2011.aspx

Activating and Invoicing Contracts in Dynamics CRM 2011
http://magnetism.co.nz/blog/simon/simon-phillipss-blog/2011/05/25/Activating_and_Invoicing_Contracts_in_Dynamics_CRM_2011.aspx

Updating execution time of the contracts state change jobs
http://mayankp.wordpress.com/2012/10/23/crm-rescheduling-the-update-contract-states-job/

Monday 8 October 2012

The column heading cannot be empty

When trying to do data import of csv file, I was getting error message "The column heading cannot be empty", when opening the file in ms-excel sheet data looks fine, with valid column names.

Reason: open the file in notepad and then will see extra coma at the end of each record including the heading this is some one tried to enter some data in excel file and then later on decided to delete the data, however ms-excel record that as a valid data column and hence the error was occurring,

Resolution: open file in ms-excel and select empty cells and rows and press delete button visually there might not be any effect but it deletes any selected empty column/rows, other wise open file in csv format and then delete unnecessary data.

Wednesday 26 September 2012

Update personal setting for all users

I am working on a project where we are suppose to send an email when ownership of a record is changed, and also on some record when some data is updated but due that we had some information which logged in user has no visibility due to security role, but we want to inform them or update data as a result of some changes done by logged in user.

To achieve there are few plugin written which are running as service account, everything seem working fine except when user's setting is to user email router to send email, in this case the logged in user is in the from however the plugin which is executing is running under service account then user gets plugin exception that he needs to update "Allow other users to send email on his/her behalf", if user sets this option by going to file->option->email tab and selects this check box than plugin executes fine.

however this needs to be done for lots of user on client site, and there is not OOB option which allows system admin to update personal setting for each user.

Solution is to write code and retrieve usersettings record and then update IsSendAsAllowed email for the required users:

Entity Name: UserSettings

Attribute Name: IsSendAsAllowed

Thursday 13 September 2012

Error while deploying crm solution

When I was trying to deploy CRM solution using CRM Develper toolkit, I was getting an error that attribute attribute2 does not exists on entity entity1 though the attribute1 and attribute2 does exists.

Solution, There was a space in attributes list in pre-image i.e. Attributes="attribute1, attribute2", removing the space solved the issue. Scool boy error

Thursday 6 September 2012

Valid email

When sending email for/from system user CRM checks whether "Primary Email-Status" for system user is approved,
for contact "emailaddress1" is considered.

error while updating security permission on secure field

I updated a field and enabled field level security. Then I created a security profile and when tried to update the security field permission I was getting error

"the user does not have read permissions to a secured field"

Solution: Publish All customisation for the solution which has the security profile


http://social.microsoft.com/Forums/en/crmdevelopment/thread/d6f898ba-2be7-4992-8820-44399a45f227

Field-Level Security

Tuesday 4 September 2012

Check wheter dialog is completed succesfully or cancelled



ProcessLogStatus:
    {
        InProgress: 1,
        Succeeded: 2,
        Failed: 3,
        Canceled: 4,
        Waiting: 5
    }


IsDialogCancelled: function (regardingobjectid) {

        var fetchXml = '<fetch mapping="logical" count="1" version="1.0">';
        fetchXml = fetchXml + '<entity name="workflowlog">';
        fetchXml = fetchXml + '<attribute name="status" />';
        fetchXml = fetchXml + '<order attribute="createdon" descending="true" />';
        fetchXml = fetchXml + '<order attribute="stepname" descending="true" />';
        fetchXml = fetchXml + '<filter />';
        fetchXml = fetchXml + '<link-entity name="processsession" from="processsessionid" to="asyncoperationid">';
        fetchXml = fetchXml + '<attribute name="regardingobjectid" />';
        fetchXml = fetchXml + '<filter>';
        fetchXml = fetchXml + '<condition attribute="regardingobjectid" operator="eq" value="' + regardingobjectid + '" />';
        fetchXml = fetchXml + '</filter>';
        fetchXml = fetchXml + '</link-entity>';
        fetchXml = fetchXml + '</entity>';
        fetchXml = fetchXml + '</fetch>';
       
        var service = new crmSOAPService(orgUniqueName, server);
        var processlogstatus = service.Fetch(fetchXml);

        if (processlogstatus != null && processlogstatus.length > 0) {

            if (processlogstatus[0].attributes.status.value == ProcessLogStatus.Canceled) {
               
                return true;

            } else {

                return false;

            }

        } else {
            return false;
        }
    }

Friday 17 August 2012

DebugView

Use Debug.Writeline("...") or Trace.WriteLine("...") and then use debugview to see the trace of execution flow.

Trace.WriteLine("..") goes into release built only

Download it from http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx

Wednesday 8 August 2012

working with excel in .net


string[] entities = new string[]{"new_custom1","new_custom3","new_custom4"};


 Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

            if (xlApp == null)
            {
                Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct.");
                return;
            }
            xlApp.Visible = true;

            Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            //Worksheet ws = (Worksheet)wb.Worksheets[1];          

            RetrieveAllEntitiesResponse retrieveallEntitiesResponse = (RetrieveAllEntitiesResponse)service.Execute(retrieveEntityRequest);

            foreach (var entityMetadata in retrieveallEntitiesResponse.EntityMetadata)
            {
                if (entityMetadata.LogicalName.Contains("new") && entityMetadata.DisplayName.LocalizedLabels.Count > 0 && entities.Contains(entityMetadata.LogicalName))
                {

                    Microsoft.Office.Interop.Excel.Worksheet newWorksheet;
                    newWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                    newWorksheet.Name = entityMetadata.DisplayName.LocalizedLabels[0].Label;
                    int columnIndex = 1;
                    foreach (var attribute in entityMetadata.Attributes)
                    {
                        if (attribute.LogicalName.Contains("new") && attribute.Description.LocalizedLabels.Count > 0 && !attribute.Description.LocalizedLabels[0].Label.ToLower().Contains("internal"))
                        {
                            newWorksheet.Cells[1, columnIndex].Value2 = attribute.DisplayName.LocalizedLabels[0].Label;
                            newWorksheet.Cells[1, columnIndex].AddComment(attribute.Description.LocalizedLabels[0].Label);

                            columnIndex++;
                        }
                    }
                }
            }

http://csharp.net-informations.com/excel/csharp-format-excel.htm

On or before x number of days


Currently in CRM filter criteria doesn't provide the facility to view records which are are valid on or before 3 days.

IOrganizationService crmService = localContext.OrganizationService;

            object query = localContext.PluginExecutionContext.InputParameters["Query"];
            if (query.GetType() == typeof(QueryExpression))
            {
                QueryExpression qe = (QueryExpression)localContext.PluginExecutionContext.InputParameters["Query"];

                FilterExpression fe = qe.Criteria;

                var filterAttributeCondition = (from c in fe.Conditions
                                                where c.AttributeName == "new_retrievemultiplefilter"
                                                select c).FirstOrDefault();

                if (filterAttributeCondition != null && (string)filterAttributeCondition.Values[0] == "records on or before x number of days")
                {

                    fe.Conditions.Remove(filterAttributeCondition);

                    var xNumberOfDaysCondition = (from c in fe.Conditions
                                                  where c.AttributeName == "new_xnumberofdays"
                                                  select c).FirstOrDefault();

                    if (xNumberOfDaysCondition != null)
                    {
                        int xNumberOfDays = xNumberOfDaysCondition.Values.Count > 0 ? (int)xNumberOfDaysCondition.Values[0] : 0;

                        fe.Conditions.Remove(xNumberOfDaysCondition);

                        DateTime dateOnXnumberDaysBefore = DateTime.Now.AddDays(-xNumberOfDays) ;


                        fe.Conditions.Add(
                            new ConditionExpression(
                                "attributename",
                                ConditionOperator.OnOrBefore,
                                new object[]{dateOnXnumberDaysBefore})
                                );
                    }
                }
            }

Dialog is not showing the many to many entity in the list to create query

When creating the Dialog, and defining the the CRM Query I was not able to see the entity which has a implicit many to many relationship.

Reason: seems to be a bug in crm 2011 product

Resolution: open the many to many relation and change the display option of "Current Entity"and "Other Entity" to "Use Plural Name"

HTML5 - CSS3

Thursday 19 July 2012

Data Import


While importing data, I was getting an SQL Internal Error when trying to import error,
There are few plugin registered on records created, and when I debuged them while importing data, the code executed fine.

The reason for the error was the length of the identifier/name of the record was defined 100 character, and the concatenation was exceeding the length of identifier/name.

Wednesday 18 July 2012

MSCRMKeyGenerator problem

Error: when trying to browse the crm page.
object reference not set to an instance of an object.

when looked at the event viewer. following is the detail message

Current key (KeyType : CrmWRPCTokenKey) is expired.  This can indicate that a key is not being regenerated correctly.  Current Key : CrmKey(Id:xxxxx-xxxx-xxxx-a602-00155d8283bf, ScaleGroupId:00000000-0000-0000-0000-000000000000, KeyType:CrmWRPCTokenKey, Expired:True, ValidOn:06/15/2012 09:59:04, ExpiresOn:07/18/2012 09:59:04, CreatedOn:06/15/2012 09:59:04, CreatedBy:NT AUTHORITY\NETWORK SERVICE.

Solution: Restart Async servcie and do a IIS Reset

Tuesday 10 July 2012

Formating Excel Sheet

To format a list of values in a column if they are not present in the list of values mentioned into another sheet column,


Select the range of cells you want to apply formatting to
Click on the Conditional Formatting
Click on the new rule

Specify formula
=countif(sheet1!b2$:c3$,d2)
select format and click apply

d2 is the first record of the selection where we are applying the formatting to.

=countif(dictionarylist,d2)
dictionarylist is the name of the cells values from where we like the values to compare to. to create a named list, select list of values, and on the left of formula where it show column name change it to some list name e.g. dicitionarylist

if you want to format a cell where values does not exits in the list than

= countif(dictionarylist,d2)=0

=if(isblank(m9),false,COUNTIF(lifecyclelist,M9)=0)

http://www.contextures.com/xlCondFormat03.html
http://www.contextures.com/xlCondFormat01.html

Wednesday 6 June 2012

Reporting services not running error while installation of crm 2011

While installation of CRM organistion I was getting error on "Reporting Services", though the reporting service was running.

Start->Microsoft Sql server 2008 R2 -> Configuration Tools ->Reporting Services Configuration Management
and make sure the required stuff is initialised

Service Account
    -> Network Service

Web Service URL
    -> Virtual Directory: ReportServer
    -> TCP Port: 80
    -> SSL Certificate: (Not Selected)


Database
     -> SQL Server Instance: devserverx
     -> Report Server Database: ReportServer
     -> Temp Database: ReportServerTempDB
     -> Report Server Language: English(United states)
     -> Report Server Mode: Native
     -> Authentication Type: Service Account
     -> Username: NT Authority\Network Service
     -> Password: *******

Report Manger URL
     -> Virtual Directory Reports


Data Error (cyclic redundancy check)


While running crm 2011 setup, I was getting following error when I was clicking next on the orgnisation creation page.

---------------------------
Microsoft Dynamics CRM Setup
---------------------------
Data error (cyclic redundancy check).
---------------------------
OK  
---------------------------

Reason: I mounted the image into CD-Rom from the remote server e.g. \\remotemachine\\folder


Solution: Copied image to local machine and mounted it to cd-rom and then installed

Friday 25 May 2012

Metadata documentation

Error registering plugins and/or workflows

Created a plugin and created a key and signed the project with that key, when deploying getting following error


"Error registering plugins and/or workflows. Public Assembly must have public key"


When checking in the crm exprlorer the plugin is registered correctly.


It was happening due to not registering the workflow project with the signed key, either remove the project if not required, otherwise deployment process also trying to deploy both plugin and workflow assembly.

Thursday 24 May 2012

how to reload a page

On entity form load i am showing a user dialog to select some values, and on completion of that dialog I am trying user to see the selection he made on the dialog are reflected on the entity form.

as there is no changes done on any attriubte using javascript, calling Xrm.Page.data.entity.save() is not gonna work.

Tried using Xrm.Page.getAttribute("new_attribute1").setValue(Xrm.Page.getAttribute("new_attribute1").getValue());
 Xrm.Page.getAttribute("new_attribute1").setSubmitMode("always");

The above couple of code lines will not work either, the reason is that though I am trying to use setSubmitMode("always"), still the data entity is not dirty,

so here is code i used make sure the page is reload by force, this following code is already with in many conditions so this code is reached when I need to reload page.

In my understanding setSubmitMode("always") is used to save a value of read only fields, or when we are making some changes on attribute and like to force entity to save.



        if (Xrm.Page.data.entity.getIsDirty()) {

            Xrm.Page.data.entity.save();

        } else {

            window.location.reload(true);

        }




/////////////////
in another scenario I wanted to save some of the values which i calculated using javascript, when there were some mandatory fields on the form are not populated and we don't like use at that moment of time to save values.




function ClearRequiredFields () {
        if (!Xrm.Page.data && !Xrm.Page.data.entity) {
            return;
        }
        var attributes = Xrm.Page.data.entity.attributes.get();
        for (var i in attributes) {
            var attribute = Xrm.Page.getAttribute(attributes[i].getName());
            if (attribute.getRequiredLevel() == "required" && !attribute.getValue()) {
                attribute.setRequiredLevel("none");
            }
        }
    }

Tuesday 22 May 2012

CRM interface customisation

http://msdn.microsoft.com/en-us/library/gg328217.aspx

On CRM Entity Navigation Area we can not add new navigation groups or remove existing one. To change the group name, select group and click on properties ribbon button.

To customise ribbon button, creating new ribbon button, hiding or un-hiding existing default crm buttons use Visual Ribbon Editor from http://crmvisualribbonedit.codeplex.com/

To customise sitemap use the SiteMap Editor which can be downloaded from

http://sitemapeditor.codeplex.com/releases/view/87898


For icons have a look at http://www.iconfinder.com/


Wednesday 16 May 2012

Dangling Entity

In org1 I created a solution with entity A, and imported it as a managed solution in org2, in org 2 I created an entity C and created a relation to entity A, later on I deleted entity A from org1 and reimported the managed solution from org1 to org2. 

The entity A still exists in org2 as it has a relation with entity C, I deleted the relationship and now I am left with a dangling entity A in org2, I can not deleted in org2 as its a managed entity imported from different org's solution. and now this entity no longer exists in org2.

The only thing I done is changed its display name to be bit descriptive saying it is no longer valid and shouldn't be used in org2.

Friday 4 May 2012

Custom activity Expected non-empty Guid

When writing custom activity for dialog process, I was getting an error " Expected non-empty Guidif I don't set the Out Argument of EntityReference type. Though the custom activity code is executing fine, this error was coming from with the workflow engine, Here is the complete error message


Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Expected non-empty Guid.Detail:
<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
  <ErrorCode>-2147220989</ErrorCode>
  <ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
    <KeyValuePairOfstringanyType>
      <d2p1:key>CallStack</d2p1:key>
      <d2p1:value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">   at Microsoft.Crm.Exceptions.ThrowIfGuidEmpty(Guid parameter, String name)
   at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.Retrieve(String entityName, Guid id, ColumnSet columnSet, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType)</d2p1:value>
    </KeyValuePairOfstringanyType>
  </ErrorDetails>
  <Message>Expected non-empty Guid.</Message>
  <Timestamp>2012-05-03T16:44:39.8508813Z</Timestamp>
  <InnerFault i:nil="true" />
  <TraceText>
[Microsoft.Xrm.Sdk.Workflow: Microsoft.Xrm.Sdk.Workflow.Activities.RetrieveEntity]
[RetrieveEntity]
Entered ContactRelationshipDefinition.Execute(), Activity Instance Id: 149, Workflow Instance Id: 9d1eb654-1cf1-4e7b-b54f-0a523ab72dc1
ContactRelationshipDefinition.Execute(), Correlation Id: 00000000-0000-0000-0000-000000000000, Initiating User: 5efdf43e-0578-e111-a01e-00155d450361
Exiting ContactRelationshipDefinition.Execute(), Correlation Id: 00000000-0000-0000-0000-000000000000
</TraceText>
</OrganizationServiceFault>


Solution: Rather then not setting  EntityReference  out argument due to some condition, set it to null.
For example

protected override void Execute(CodeActivityContext context)
{
//outputParameterName is the outpurt parameter, if there are more then one the set all those to null as well.
     context.SetValue<EntitiyReference>(outPutParamenterName,null)

  //custom logic goes here
}

Wednesday 28 March 2012

Assembly must be registered in isolation

Xrm.Page.ui is null, Xrm.Page.data is null, Xrm.Page.data.entity.getId() is null for navigation subgrid javascript

I was trying to add enable role on ribbon button of a Entity B which is shown when I click on the navigation link of entity A. In the custom javascript I needed the Entity A id, and Xrm.Page.data.entity.getId() was not available,and same was the case with Xrm.Page.data and Xrm.Page.ui.

After doing bit of investigation, I found out that the javascript conext for ribbon bar is running in iframe of entity B, and to access the entity A values I have to use window.parent.Xrm.Page.data.entity.getId()


http://social.microsoft.com/Forums/en-US/crmdevelopment/thread/8cfe6ff6-7569-48e2-b87e-359280204162/

Tuesday 20 March 2012

setting the id value to entity attribute and getting error "can not be null"

This is due to I was setting the attribute to Id rather then the entity reference object.

Thursday 15 March 2012

Update parent entity page

Added a subgrid of related entity on a Entity A form. When opening the related record from child I am updating some values on form and need to update the parent form. On child page add following jscript for custom button


window.parent.opener.parent.location.reload();
Xrm.Page.ui.close();

When sending email getting message "Some error occured"


When sending an email on change of ownership of record, I was getting error "some error occurred", to resolved it set the caller id "on behalf of" as below


            EntityReference callingUser = new EntityReference
            {
                LogicalName = "systemuser",
                Id = localContext.PluginExecutionContext.InitiatingUserId
            };

            OrganizationServiceProxy serviceProxy = (OrganizationServiceProxy)crmService;
            serviceProxy.CallerId = callingUser.Id;

Friday 9 March 2012

Microsoft.Crm.CrmException: The user Id is invalid

I successfully created a new crm organisation system, and when I tried to browse at the org, I was getting following error "Microsoft.Crm.CrmException: The user Id is invalid",

The issue was I was running the CrmAppPool with a domain account which was not the administrator/the user which I used to create crm organisation. As the apppool user was not present initially in the crm org users, I was getting above error, moved the crmapppool to network service, then recreated the org and then added the user and then added the updated the crmapppool user back to domain service/user.

Thursday 8 March 2012

ribbon is disabled when form navigation is used

Xrm.Page.ui.formSelector.items.get(formId).navigate( );

I used the form navigation in different scenarios, and It worked fine, however in the current scenario when I call
Xrm.Page.ui.formSelector.items.get(formId).navigate( ); when the form is reloaded I was getting error on page message, I am not sure about what was causing the issue, the patch I applied was setting the setTimeout function and then called the navigate function from it.

Wednesday 7 March 2012

Crm2011 using rest end point in javascript

I have an entity Subject, and related entity Result. when marks are set in subject. Result entity is reterived and all subjects of Result entities are reterived where subject is not droped. and finally Result entity overall marks are updated.

Add follwoing javascript files to entity on load event.
jquery1.4.1vsdoc, json2, JQueryRESTDataOperationFunctions and finally here is javascript to update related entity value depending on current values.

statuscode on Subject is either selected or droped. On form load call Loaded function and on form save call UpdateResultDetails.
As ajax call are made in order to complete given task select  "pass execution context as first parameter "in order to manually control saving and closing of form.

/// <reference path="jquery1.4.1vsdoc.js" />
/// <reference path="JQueryRESTDataOperationFunctions.js" />

var initialSubjectStatus;
var saveMode;
//used to stop recursive saving
var saveFlag = false; 

//initialises application status
function Loaded() {
    initialSubjectStatus = Xrm.Page.getControl("statuscode").getAttribute().getValue();
}

function UpdateResultDetails(ExecutionObj) {    
    if (Xrm.Page.data.entity.getIsDirty() && !saveFlag) {

        var applicationstaus = Xrm.Page.getControl("statuscode").getAttribute().getValue();

        //checks whether Subject status initially was selected or is currently is selected
        if (initialApplicationStatus == 161820001 || applicationstaus == 161820001) {
            if (ExecutionObj) {
                ExecutionObj.getEventArgs().preventDefault();

                //Save = 1, Save and Close = 2 , Save and New = 59 ...
                saveMode = ExecutionObj.getEventArgs().getSaveMode();
            }
            retrieveResult(Xrm.Page.getControl("publisher_resultid").getAttribute().getValue());
        }
    } else {
        saveFlag = false;
    }
}

function retrieveResult(idObj) {
    if (!idObj) {
        return;
    }

    retrieveRecord(idObj[0].id, "publisher_resultSet", retrieveResultCompleted, null);
}

//reterive subjects for specified result id
function retrieveSubjects(resultId) {

    if (Xrm.Page.data.entity.getId() == null) {
        //subject is selected
        retrieveMultiple("publisher_subjectSet", "?$filter=publisher_resultId/Id eq (guid'" + resultId + "')  and (statuscode/Value eq 161820001)", retrieveSubjectsCompleted, null);
     } else {
        //subject status is selected
        retrieveMultiple("cnova_subjectSet", "?$filter=publisher_resultId/Id eq (guid'" + resultId + "')  and (statuscode/Value eq 161820001) and not (publisher_subjectId eq (guid'" + Xrm.Page.data.entity.getId() + "'))", retrieveSubjectsCompleted, null);
    }
}

var vacancy;

function updateResult(numberOfSubjectsSelected) {
    if (!subject.publisher_TotalNumberOfSelectedSubjects) {
        return;
    }
    var remainingsubjects = subject.publisher_TotalNumberOfSelectedSubjects - numberOfSelectedSubjects;

    var applicationstaus = Xrm.Page.getControl("statuscode").getAttribute().getValue();
    if (applicationstaus == 161820001) {
        remainingsubjects--;
    }

    if (remainingsubjects < 0) {
        remainingsubjects = 0;
    }

    var changes = new Object();
    changes.publisher_RemainingNumberOfSubjects = remainingpositions;

    if (remainingsubjects > subject.publisher_TotalNumberOfSelectedSubjects) {
     subject.publisher_TotalNumberOfSelectedSubjects = remainingpositions;
    }

    updateRecord(result.publisher_resultId, changes, "cnova_resultSet", ResultUpdated, null);
}

function retrieveSubjectsCompleted(data, textStatus, XmlHttpRequest) {
    updateResult(data.length);
}

function retrieveResultCompleted(data, textStatus, XmlHttpRequest) {
    result = data;
    retrieveSubjects(result.publisher_resultId);
}

function ResultUpdated() {
    saveFlag = true;

    if (saveMode == 1) {
        Xrm.Page.data.entity.save(null);
    }
    else if (saveMode == 2) {
        Xrm.Page.data.entity.save("saveandclose");
    }
    else if (saveMode == 59) {
        Xrm.Page.data.entity.save("saveandnew");
    }
}


Hiding a Ribbon Button

Monday 5 March 2012

CRM Development Toolkit deploy error


Error 1 Error registering plugins and/or workflows. The resource string "ErrorSerializingRegFile" for the "RegisterPlugin" task cannot be found. Confirm that the resource name "ErrorSerializingRegFile" is correctly spelled, and the resource exists in the task's assembly. C:\Program Files (x86)\MSBuild\Microsoft\CRM\Microsoft.CrmDeveloperTools.CrmClient.targets 176 4 CrmPackage

Solution:
RegisterFile.crmregister file is checked in, Check out file manually.

Ignore a code block while debugging


[DebuggerStepThrough]