Showing posts with label Early Bound. Show all posts
Showing posts with label Early Bound. Show all posts

Saturday, 9 May 2015

How to Solve: Could not load type 'Xrm.XrmServiceContext'

Problem Introduction

It is very often to see this error, especially when you are developing a custom app/website connecting to CRM using Portal Extension method or Simplified Connection.

image

And actually, I learn it from mistake, I realized my mistake, small mistake that making my example not working.

So here is the step to resolve:

Have you followed this step?

https://msdn.microsoft.com/en-us/library/gg695790.aspx
When I say ‘have you’, are you really really comfortable to say yes? Have you really-really followed the instruction?
Well, if you think you ‘have’, it is not your fault, because I also did the same thing.
Now, I still face the error…What should I do?

1. Are you using the correct framework?

If you are using CRM 2015, then you should use .NET 4.5.2.
For CRM 2013, you should use .NET 4.5
And for CRM 4.0 is .NET 4.0

2. Try to check whether you have inserted the generated code

Please check again in your Project, have you inserted the generated code you generated from CrmSvcUtil?

3. Check again your web.config and ContextTypeName (in the ASPX) vs CRMScvUtil Parameters

This is very important, because this was the root of failure I did not realize before.
Here, you need to check first the CrmSvcUtil..
In fact..I generate this:

CrmSvcUtil Parameters

CrmSvcUtil.exe /codeCustomization:"Microsoft.Xrm.Client.CodeGeneration.CodeCustomization,Microsoft.Xrm.Client.CodeGeneration" /url:"https://aileenexample.api.crm5.dynamics.com/XRMServices/2011/Organization.svc" /out:"XrmContext.cs" /username:admin@aileenexample.onmicrosoft.com /password:passwordme /namespace:Xrm /serviceContextName:"XrmContext"
pause 

You seem my parameter for serviceContextname is “XrmContext”, not the “XrmServiceContext”!!

While I check my web.config:

Web.Config

<microsoft.xrm.client>
    <contexts>
      <add name="Xrm" type="Xrm.XrmServiceContext, Xrm.CRM.2015.WebExample" />
    </contexts>
</microsoft.xrm.client>

And also I check my .ASPX code
<asp:LinqDataSource ID="Contacts" ContextTypeName="Xrm.XrmServiceContext" TableName="ContactSet" runat="server" />

Well, I use both in my code :

Xrm.XrmServiceContext

While, I generate the code using servicecontext parameter to this:

image

Of course, it wont be able to load the type.

Then, what I do is, I change my web.config and my ASPX from

Xrm.XrmServiceContext

to

Xrm.XrmContext

Or you can re-generate the file and change the the /serviceContextName param from

“XrmContext” to “XrmServiceContext”

It is common mistake and sometimes is hard to realize!

Tips: Since you can have many changes in your CRM Metadata, you might need to re-generate your generated code very often, then I recommend you to consider the batch execution approach.

See this for detail:

http://missdynamicscrm.blogspot.sg/2014/05/crm-sdk-smart-way-to-use-crmsvcutilexe.html

Hope this saves your day!

Thanks!

Convert XrmServiceContext to the IOrganizationService

A Quick post, If you use the Early Bound and you use the XrmContext strong-typed type method, but you think you miss the way you initialize the IOrganizationService in CRM, you can convert it by typing the following code..

XrmContext xrmContext = new XrmContext();
IOrganizationService service = xrmContext;

image

Hereafter, you can access your service object easily.

Hope this helps.

Thanks.

Friday, 23 May 2014

CRM 2011/2013 The Power of Description

When you create a New Field, often, we just put the name of the field, that’s all and does not care the others, since it is not mandatory as well.

Sometimes Description is important, don’t underestimate its function, and don’t just let it blank. It can save your life later, I am seriously saying like that Smile

Okay, let’s go to a custom field in Account as example.

Let’s say I create a custom field to link Account with Country, I replace the text field standard field Address 1: Country to this field, then put in the Form to get the field in the Template.

First, we download the Import Template for Account, then get this one :

image

Well, we can see the tooltip description, actually it gives nothing, but just a common information, who care about this.

Then, you give a proper description on this field.

image

Then, save this.

There are 7 advantages so far I can tell because of this field.

1. I create a custom field, then I give information about this, so that my project mate also can see this field and its information, “what is my purpose”, and “what is its usage”.

Then, later, next 2 years, maybe customer wants to upgrade the version of CRM, then I might be forgot already why I should create this field?

2. When you want to see the detail of the field in the Form.

image

3. In the Form, I can help user to know what the field is.

In CRM 2013, we can have a tooltip, if in CRM 2011, the tooltip is the from the Label Name only.

image

4. In the Data Template

image

It gives you clearer Information, not just only say, it is “Unique identifier…”

5. In the time of making Processes

image

6. It saves your time to create a Documentation.

You are as Consultant then want to create a Functional Design Document, you can use tool to generate the Metadata.

image

And you can get the result, s not only showing the standard information for the Description field.

image

Well, if number 1-5, they will help Functional Consultant and Users, now let’s help your Technical Consultant or the one who Develop the custom code.

7. To make it enable in the Early Bound Class

image

Yes, it is very helpful if your field is not easy to be guessed, such as hidden or special field for flag, so better way is by giving the field a proper detail description.

Do you find another advantage for number 8? Then, comment and tell us!

Thanks and hope it helps!

Tuesday, 20 May 2014

CRM 2011 / 2013 Convert Late Bound Entity Class to Early Bound

In the plugin code, first you will get the Entity class :

// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];

Sometimes, you need to have logic using Early Bound for this entity class for easier life.

Here you can achieve this :

//create target entity as early bound
Opportunity targetEntityEarlyBound = entity.ToEntity<Opportunity>();

*Opportunity is your Target Entity Class

Congratulation, now you can use the Early Bound for target entity on your plugin.

image

Hope it helps!

Tuesday, 13 May 2014

CRM 2013 Custom Action as Next Action

As we know that Custom Action gives you a special capability to extend xRM Platform and it gives a great future.

At My Previous Post I was talking about Custom Action as Validation Gate and many of my posts are related to Custom Action.

Now, I would like to show you about Custom Action that not only as validation, but also can give you a new idea to do next action.

Now, start with my previous custom action, but I will not only use that for giving this Business Error :

image

I would like to put 5600 to fill one of my field value in Quote :

image

Because actually, I already did pass the Quote entity to my Custom Action, remember this snippet :

image

Actually, there are two possibility ways to do :

1. Getting an Output, still getting an output from the custom action then in my plugin I set my Revenue field value based on the output from my custom action, rather than I just throwing an error, which is I get that 5600.0

2. I use my custom action to update my Revenue field.

This is what I did is using the number 2, because I want my plugin is only calling my custom action and all of the logic will be done by my custom action, my plugin no need to do anything anymore since this custom action will be called by anywhere, for example if I have an calculator apps in my web or my agent desktop app, etc.

Then, I modify my code in Action Code :

public class Action_SimpleCalculation : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            #region must to have

            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

            // Create service with context of current user
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            //create linq context
            KonicaBaseContext baseContext = new KonicaBaseContext(service);

            //create tracing service
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            #endregion

            //To get access to the image of the Quote record
            EntityReference entityRef = context.InputParameters["Target"] as EntityReference;
            
            //To read the input parameter
            Money money1 = context.InputParameters["Money1"] as Money;
            Money money2 = context.InputParameters["Money2"] as Money;

            //Capture Discount Rate
            decimal discount = 0;
            discount = (decimal) context.InputParameters["Discount"];

            //Now, I am talking about Custom Action as Validation Gate
            if(discount >= 100)
            {
                throw new InvalidPluginExecutionException("Hi, are you crazy to give such discount? We will not gain any profit, do you realize that?!");
            }

            else{
                //This is how the calculation works and custom action as a Calculation Formula
                Money sum = new Money(money1.Value + money2.Value);
                Money sumafterDiscount = new Money();
                sumafterDiscount = new Money(sum.Value - ((sum.Value) * (discount / 100)));

                //using this as a response output
                context.OutputParameters["MoneySum"] = sumafterDiscount;

                //rather than only giving me an output, I would like to call next action, that is update the revenue field in my quot
                //I already have my quote Id

                Quote myQuote = new Quote();
                myQuote.Id = entityRef.Id;
                myQuote.tfp_Revenue = sumafterDiscount;
                service.Update(myQuote);
           }
        }
    }

Then in my Plugin I just call my Action

//create target entity as early bound
                    Quote TargetEntity = entity.ToEntity<Quote>();

                    //call Business Layer
                    QuoteBL quoteBL = new QuoteBL();
                    
                    //Money moneySum = quoteBL.ExecuteCustomAction_SimpleCalculation(service, new Money(2000), new Money(5000), TargetEntity.Id) ;
                    //throw new InvalidPluginExecutionException("Hi, your total Amount will be = " + moneySum.Value.ToString());

                    //this one to prevent infinite loop, because custom action will update the revenue
                    if (TargetEntity.tfp_Revenue != null)
                    {
                        return;
                    }

                    //just call my custom action
                    quoteBL.ExecuteCustomAction_SimpleCalculation(service, new Money(2000), new Money(5000), TargetEntity.Id);

I don’t call the “throw new InvalidPluginExecutionException” anymore, but I call my Custom Action, instead.

After you saved to trigger plugin and custom action, you can test it and here is your expected result :

image

Hope it helps!

CRM 2013 Custom Action as Validation Gate

In My Previous Post I was talking about Custom Action in Microsoft Dynamics CRM 2013 as Custom Message and also I give example about utilizing Custom Action as Calculation Formula.

Now, I will still using the same Custom Action as Example, but I will add some logic to make it as Validation Gate.

Imagine that you have several application that need connect to your CRM and do the same calculation, then you have to copy paste your custom code to all of the apps and do the validation.

Let’s go to the example with still using same custom action but adding some sauce : Discount

image

Then, I amend my code to give some validation :
public class Action_SimpleCalculation : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            #region must to have

            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

            // Create service with context of current user
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            //create linq context
            KonicaBaseContext baseContext = new KonicaBaseContext(service);

            //create tracing service
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            #endregion

            //To get access to the image of the Quote record
            EntityReference entityRef = context.InputParameters["Target"] as EntityReference;
            
            //To read the input parameter
            Money money1 = context.InputParameters["Money1"] as Money;
            Money money2 = context.InputParameters["Money2"] as Money;

            //Capture Discount Rate
            decimal discount = 0;
            discount = (decimal) context.InputParameters["Discount"];

            //Now, I am talking about Custom Action as Validation Gate
            if(discount >= 100)
            {
                throw new InvalidPluginExecutionException("Hi, are you crazy to give such discount? We will not gain any profit, do you realize that?!");
            }

            else{
                //This is how the calculation works and custom action as a Calculation Formula
                Money sum = new Money(money1.Value + money2.Value);
                Money sumafterDiscount = new Money();
                sumafterDiscount = new Money(sum.Value - ((sum.Value) * (discount / 100)));

                //using this as a response output
                context.OutputParameters["MoneySum"] = sumafterDiscount;
            }
        }
    }

Then, I also add parameter to call this action :
#region custom action execution

        //EARLY BOUND
        public Money ExecuteCustomAction_SimpleCalculation(IOrganizationService service, Money money1Param, Money money2Param, Guid quoteId)
        {
            tfp_Action_SimpleCalculationRequest request = new tfp_Action_SimpleCalculationRequest()
            {
                Money1 = money1Param,
                Money2 = money2Param,
                Target = new EntityReference("quote", quoteId),
                //new parameter
                Discount = 120
            };

            tfp_Action_SimpleCalculationResponse response = service.Execute(request) as tfp_Action_SimpleCalculationResponse;
            //Processing of response
            return response.MoneySum;
        }
        #endregion



Update your Plugin Assembly then see the result.

And yeah, this is the result

image

Now, change the discount again to less than 100.

image

Then Update your plugin.

Here is the result :

image

Hope it helps!
Thank you.

CRM 2013 Register Custom Action as an Advance Custom Message

Action in CRM 2013 is a great feature.
In my previous posts, I have talked about Action :

All about Custom Action

Then I also have many example to utilize Action to cater my idea extending xRM Platform.
Now, I am explaining Custom Action as Custom Message that enable for developer to Register as a Step in Plugin Registration Tool!

This is very useful when you want to do integration or calling a server side complex business logic, for example Calculation and Validation.

But, there is a doubt that in Steps, you can only do simple thing, nothing to do? Then, how?
These standard steps of CRM 2013 Action are very limited and nothing much different with other Workflow.

image

If you think that Available Steps in Action is not be able to accommodate what you want, then? Then, Customize it, do advance customization on it.

Now, first let me guide you. I give you example how to extend Custom Action as Custom Message, I don’t want to give a complex sample now, just give you a concept to understand.

I give you sample how to do calculation with Formula : Money1 + Money2 = MoneySum.

Two input arguments : Money 1 and Money 2
One outpur argument : Money Sum

1. Create an Action (You can refer to my above links, and also from that link you can see any links to talk about Action in CRM 2013)

Create your own Message : SimpleCalculation, for example (and give some prefix to indicate it)
(Remember, this is will be your custom message, a verb, a message, that you will use as your universal code contract to be registered to be used by any custom code, just make sure you give them a proper name).
Define your argument as well


image

2. Why no steps?

I want to let you know that you also can create your logic instead using those standard steps.

3. Activate it.

4. Generate an Early Bound Class to get your action in your class library

Please refer to this article :

Generate Custom Action as Early Bound

You also can use Early Bound and Late Bound, but for easier way, I use Early Bound as a sample.

5. Create a Plugin Class and put this code :

public class Action_SimpleCalculation : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            #region must to have

            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

            // Create service with context of current user
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            //create linq context
            KonicaBaseContext baseContext = new KonicaBaseContext(service);

            //create tracing service
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            #endregion

            //To get access to the image of the Quote record
            EntityReference entityRef = context.InputParameters["Target"] as EntityReference;
            
            //To read the input parameter
            Money money1 = context.InputParameters["Money1"] as Money;
            Money money2 = context.InputParameters["Money2"] as Money;

            Money sum = new Money(money1.Value + money2.Value);

            //using this as a response output
            context.OutputParameters["MoneySum"] = sum;
        }
    }

6. Register Your Class as Plugin using Plugin Registration Tool
(You might have to refresh your Plugin Registration Tool until you can see your Action as Message)

image

Register your step :

image

7. Call your Action from your Code

image

8. Pass to your Execution Code your own parameter

image

For example : 2000 and 5000, and pass your Quote Id as Target Entity (if you have this specific entity when you create your Action)

Then, your Total Amount will be : 7000 from 2000 + 5000
Throw an error message for capturing your Total Amount.

Let’s test it, run your code!

9. Test your code by triggering your custom code (In this case I call my Action after my Quote updated)

Here is the result :

image

Here, I don’t put any logic in my Plugin, I just using one single point, that is Custom Action.

Next time, my logic has been changed, I don’t need to change my plugin logic or any custom code about my calculation, because I only implement my code in this Action.

Hope it is informative for you!

CRM 2013 Utilize Custom Action as Dynamics Error Message

Many times during my project development and implementation, I have requirement to Alert user if they have to input some field, those some fields sometimes is not mandatory during the Form, but it is mandatory for our Logic.

For example, in the Account entity creation or update.

- In Contact entity, City is not mandatory for some accounts type.

- If Contact Role is an Influencer, then their address will be very important to you, including City, State, and Country to complete your Addresses.

- If Contact Role is an Owner, then same as well, their complete address will be mandatory.

- If Contact Roles is not an Influencer nor an Owner then, Address fields will be only Optional or Recommendation.

So, you cannot make the Address fields as Mandatory for all of Situation, yes, you can achieve this by using JS or Business Rules, but remember that if you Form script, then let’s say user do inserting using backend such as other application or using excel import wizard, then you are forced to use Plugin to validate. Lets say you have to implement this in Lead, Account, and Contact, then this is applied to Create and Update Messages, right.

So, what possible situation is by creating a plugin that calls this :

image_thumb1

And I put them to all of my coding.
That’s fine, yes that’s Okay, and it worked.

Then what happened if my user said : Hi, I don’t want to use that messages.
Often, developer use their own way and words to spread an alert, that is not acceptable by some business users because this is till blur and unclear.

So, let’s say first you say : “Please input ‘blabla’ Value!!”, then user said, please change to : “‘blabla’ Value Cannot be Blank”, then change again to more polite command : “Hi Sir/Madam, Please don’t forget to fill the ‘blabla’ Value. Thanks”, then what will you do?

Okay, you have to change all of your Code, it is fine since you just copy paste, but you have various word for ‘blabla’ right? It can be City, State, Country, Fax, Mobile Phone, Membership ID, or whatever you have. So, yes, this is sometimes annoying.

Then, what I did in CRM 2011 is I create an entity, similar to Configuration entity to store my own Error Messages

Key Name
Key Value
Parameter Type
Description
CityBlank
Please input ‘City’ Value
Error Message
Error message if City Blank
StateBlank
Please input ‘State Value
Error Message
Error message if State Blank
CountryBlank
Please input ‘Country Value
Error Message
Error message if Country Blank

Imagine you have many fields, then you have to change all of the Key Value.
It is okay, maybe you can utilize the string.format Message to make the City, State, Country, etc as dynamic value.

But, do you know that in CRM 2013, you can utilize custom action to make your own Error Message more dynamic? This is the more elegant idea to work with Action to get some dynamic Error Message.
If you have known familiar with Action, please refer to this link :

http://aileengusni.blogspot.com/2014/05/crm-2013-let-me-introduce-nice-new_2810.html
http://aileengusni.blogspot.com/2014/05/crm-2013-custom-action-as-configuration.html

Here are the steps :

1. Create an Action

Create-custom-action1_thumb2

2. Define your Arguments

Input : FieldName – String – Required – Input
Output : MessageOutput – String – Required – Output

Define Argument custom action 2_thumb

3. Define your Steps by Assigning the Value

Set-Message-Output-3_thumb2

In this step, using your Input Argument you can create a Dynamic Output, using that FieldName input argument as dynamic value, based on what you pass as input.

4. After define your arguments and Activate your Custom Action

Activate-CA-4_thumb4

5. Using .NET in Plugin you can call your Custom Action

Early Bound

coding-to-call2_thumb3

Late Bound
Call-custom-action-late-bound_thumb3

Call that action in your Plugin
coding-to-call1_thumb2

Here is the code
//EARLY BOUND
        public string ExecuteCustomAction_PleaseInputValue(IOrganizationService service, string strFieldName)
        {
            tfp_Action_PleaseInputValueRequest request = new tfp_Action_PleaseInputValueRequest()
            {
                FieldName = strFieldName
            };

            tfp_Action_PleaseInputValueResponse response = service.Execute(request) as tfp_Action_PleaseInputValueResponse;
            //Processing of response
            return response.MessageOutput;
        }

 //LATE BOUND
        public string ExecuteCustomAction_PleaseInputValue(IOrganizationService service, string strInputParameter, string strInputParameterValue, string strOutputParameter)
        {
            OrganizationRequest req = new OrganizationRequest("tfp_Action_PleaseInputValue");
                    req[strInputParameter] = strInputParameterValue;
                    //execute the request
                    OrganizationResponse response = service.Execute(req);
            return response[strOutputParameter].ToString();
        }

For Reference :

http://a33ik.blogspot.co.il/2013/10/custom-actions-walkthrough-for-net-and.html

To generate Action in Early Bound Class :

http://aileengusni.blogspot.com/2014/05/crm-2013-generate-custom-action-as.html

6. Here is your result

When City is Blank

Business-Process-output-5_thumb4

7. Here if you want to change your Error Message, just change it :

- Go back to your Action
- Deactivate first

image_thumb[1]

- Change the steps

image_thumb[3]

8. Here is your result

image_thumb[6]

Enjoy it!

For your information, for importing Action it can be a big deal in CRM 2013, at least until Rollup 2
Please refer to this :

http://aileengusni.blogspot.com/2014/05/crm-2011crm-2013-import-solution-error.html

Hope it helps!

CRM 2013 Generate Custom Action as Early Bound

I really love to use Custom Action, it opens my mind to extend xRM Platform capability and make my job for Integration and Dynamic job easier.

I can use Action for Integration Message make it as single verb and key integration single point, and also can utilize this to combine my logic and show error message.

Because of that, I think I have to include custom action to my custom development, and sometimes, Early Bound is making my life easier.

Here is the steps you to generate Custom Actions as your Early Bound class library.

1. Download CRM 2013 SDK
2. Using CrmSvcUtil.exe

Generate Early Bound Custom Action

3. Define your own Server URL and Output file (location and namespace).

Don’t forget to add this parameter :

/generateActions

4. Here is my complete commands as example :

CrmSvcUtil.exe /url:"http://aileengusnidev:5555/contoso/XRMServices/2011/Organization.svc" /out:"../Crosscutting/BaseContext.cs" /domain:mycrmdev /username:administrator /password:mypassword /serviceContextName:"BaseContext" /namespace:TFP.Xrm.Contoso /generateActions


Remember you can save this as .bat file, so every time you need it, just run it!

For smart way, you can refer to this link : http://missdynamicscrm.blogspot.com/2014/05/crm-sdk-smart-way-to-use-crmsvcutilexe.html

CRM SDK : Smart Way to Use CRMSVCUTIL.EXE

Many times, we have to update entity and field during development, then if you are using Early Bound to save your time, here is I give you advice to update your basecontext class using CRMSVCUTIL.exe wisely.

1. Create Folder for your Output
2. Create a special folder I usually call as SDK
3. Put CrmSvcUtil.exe inside together with all of required .dll

image

4. Create a new File

image
CrmSvcUtil.exe /url:"http://aileengusnidev:5555/contoso/XRMServices/2011/Organization.svc" /out:"../Crosscutting/BaseContext.cs" /domain:mycrmdev /username:administrator /password:mypassword /serviceContextName:"BaseContext" /namespace:TFP.Xrm.Contoso /generateActions

5. Then save it as .bat file

6. Run your ,bat file

7. Back to your output folder you should find your File

image

8. Every time you have any update, then just execute your .bat file to update this.

Updated :

/generateActions is the additional parameter for CRM 2013 to including custom Action in Early Bound Class.

Hope it helps!