Friday 29 June 2012

set and get some fileds in dynamic crm 2011

Senario:

how to read the Optional set value in the Dynamic crm 2011:

OptionSetValue type =(OptionSetValue) entity1["new_billingtype"];

DateTime start = Convert.ToDateTime(entity1["new_startdate"]);
                DateTime end = Convert.ToDateTime(entity1["new_enddate"]);
                TimeSpan span = end.Subtract(start);
                if (type.Value ==100000000) //Monthly
                {
                   totalmonths = span.Days / 30;
                }

how to read money field:


Money totallineamount = (Money)contact1["totallineitemamount"];

doing calculations with int field:


int fixdiff = Convert.ToInt32(contact1["new_fixeddifference"]);
Money invoicetotallineamt = new Money() { Value =(totallineamount.Value / fixdiff) };

Set the money field:


incidentEntity["totallineitemamount"] = invoicetotallineamt;

reading lookup field:


EntityReference customerref = (EntityReference)contact1["customerid"];

          

 Set the Lookup field

    Entity incidentEntity = new Entity();
                incidentEntity.LogicalName = "invoice";              
                incidentEntity["customerid"] = customerref;

Retrieve all records:


ColumnSet cols = new ColumnSet(true);
                var contact1 = service.Retrieve("salesorder", workflowcontext.PrimaryEntityId, cols);






plugin for calculate the time difference in dynamic crm 2011

Senario: need to calculate the time difference in varios options.

using early bound.

Ex:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xrm;
using System.Diagnostics;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System.Windows.Browser;
using System.Net;
using System.IO;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Client;

namespace Kryptos.Plugin.InvoiceonBillingtype
{
    public class Dayscalculate:IPlugin
    {

        public IOrganizationService service;
        public IPluginExecutionContext context;

        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)
            serviceProvider.GetService(typeof(IPluginExecutionContext));

            Entity entity;

            // Check if the input parameters property bag contains a target
            // of the create operation and that target is of type Entity.
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {

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

                // Verify that the entity represents a contact.
                if (entity.LogicalName != "salesorder")
                {
                    return;
                }
            }

            else
            {
                return;
            }


            try
            {
                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                int totalmonths=0;
                Entity entity1 = (Entity)context.InputParameters["Target"];
                // Guid id = entity1.Id;

                OptionSetValue type =(OptionSetValue) entity1["new_billingtype"];

                DateTime start = Convert.ToDateTime(entity1["new_startdate"]);
                DateTime end = Convert.ToDateTime(entity1["new_enddate"]);
                TimeSpan span = end.Subtract(start);
                if (type.Value ==100000000) //Monthly
                {
                   totalmonths = span.Days / 30;
                }
                if (type.Value == 100000003) //Bi-Monthly
                {
                    totalmonths = span.Days / 60;
                }
                if (type.Value == 100000001) //Quarter
                {
                    totalmonths = span.Days / 90;

                }
                if (type.Value == 100000004) //Half Yearly
                {
                    totalmonths = span.Days / 180;

                }
                if (type.Value == 100000002) //Yearly
                {
                    totalmonths = span.Days / 365 ;

                }
                //TimeSpan span = end.Subtract(start);
                entity1["new_days"] = totalmonths;//span.Days;
                entity1["new_nextinvoice"] = start;

                service.Update(entity1);
            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                throw new InvalidPluginExecutionException("An error occurred in the plug-in.  "+ ex.Message.ToString());
            }

        }

    }
}

custom workflow for create a record in dynamic crm 2011

senario: here we need to create a record in custom workflow.

need to do early bound.

Ex:


using System;
using System.Collections.Generic;
using System.Text;
using System.Activities;
using System.ServiceModel.Description;
using System.Workflow.ComponentModel;
//using System.Text;
using System.ServiceModel;
//using Microsoft.Crm.Sdk.Metadata;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
//using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Xrm.Sdk.Workflow;

namespace create_invoice_record
{
    public class invoicerecord : CodeActivity
    {
        protected override void Execute(CodeActivityContext executionContext)
        {
            try
            {
                //Create the context and tracing service
                IExecutionContext context = executionContext.GetExtension<IExecutionContext>();
                IWorkflowContext workflowcontext = executionContext.GetExtension<IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                ITracingService tracer = executionContext.GetExtension<ITracingService>();

                ColumnSet cols = new ColumnSet(true);
                var contact1 = service.Retrieve("salesorder", workflowcontext.PrimaryEntityId, cols);

                string ordername = contact1["name"].ToString();
                EntityReference customerref = (EntityReference)contact1["customerid"];
                EntityReference priceref = (EntityReference)contact1["pricelevelid"];
                Money totallineamount = (Money)contact1["totallineitemamount"];
                Money discountamt = (Money) contact1["discountamount"];
               Money taxamt = (Money)contact1["totaltax"];
               Money totalamt = (Money)contact1["totalamount"];
               int fixdiff = Convert.ToInt32(contact1["new_fixeddifference"]);

               Money invoicetotallineamt = new Money() { Value =(totallineamount.Value / fixdiff) };
               Money invoicediscountamt = new Money() { Value = (discountamt.Value / fixdiff) };
               Money invoicetaxamt = new Money() { Value = (taxamt.Value / fixdiff) };
               Money invoicetotalamt = new Money() { Value = (totalamt.Value / fixdiff) };


                Entity incidentEntity = new Entity();
                incidentEntity.LogicalName = "invoice";

                incidentEntity["name"] = ordername;
                incidentEntity["customerid"] = customerref;
                incidentEntity["pricelevelid"] = priceref;
                incidentEntity["totallineitemamount"] = invoicetotallineamt;
                incidentEntity["discountamount"] = invoicediscountamt;
                incidentEntity["totaltax"] = invoicetaxamt;
                incidentEntity["totalamount"] = invoicetotalamt;

                CreateRequest createrecord = new CreateRequest()
                {
                    Target=incidentEntity
                };


                CreateResponse res = (CreateResponse)service.Execute(createrecord);
              
                              


                //ClientCredentials Credentials = new ClientCredentials();



            }

            catch (Exception ex)
            {
                //Helpers.Throw(String.Format("An error occurred in the {0} workflow.",
                //        this.GetType().ToString()),
                //      ex);
                throw new InvalidPluginExecutionException("An error occurred in the plug-in.  ", ex);
            }
        }

    }
}


custom workflow for increment or decrement field value in dynamic crm 2011

Senario: we need to set a value to one field in dynamic crm 2011 form

ex:


using System;
using System.Collections.Generic;
using System.Text;
using System.Activities;
using System.ServiceModel.Description;
using System.Workflow.ComponentModel;
//using System.Text;
using System.ServiceModel;
//using Microsoft.Crm.Sdk.Metadata;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
//using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Xrm.Sdk.Workflow;




namespace Kryptos.invoiceonbilltype.calculation
{
    public class calculatedifference:CodeActivity
    {
        protected override void Execute(CodeActivityContext executionContext)
        {
            try
            {
                //Create the context and tracing service
                IExecutionContext context = executionContext.GetExtension<IExecutionContext>();
                IWorkflowContext workflowcontext = executionContext.GetExtension<IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                ITracingService tracer = executionContext.GetExtension<ITracingService>();

                int value = InvoiceTimes.Get(executionContext);// for ex :1
                int invoice = InvoiceDate.Get(executionContext);//for ex: 30

                //Guid id = (Guid)context.InputParameters["Id"];
                //Guid id = (Guid)workflowcontext.InputParameters["id"];
                ColumnSet cols = new ColumnSet(new String[] { "new_days", "new_nextinvoice" });
                var contact1 = service.Retrieve("salesorder",workflowcontext.PrimaryEntityId , cols);

                if (contact1.Attributes.Count != 0)
                {
                    DateTime nextinvoice = Convert.ToDateTime(contact1["new_nextinvoice"]);

                    int invoices = Convert.ToInt32(contact1["new_days"]);

                 DateTime nexti =   nextinvoice.AddDays(invoice);

                    int invoicesleft = invoices - value;

                    Entity incidentEntity = new Entity();
                    incidentEntity.LogicalName = "salesorder";

                    incidentEntity["new_days"] = invoicesleft;//nextinvoice;
                    incidentEntity["new_nextinvoice"] = nexti;//invoicesleft;

                    incidentEntity["salesorderid"] = workflowcontext.PrimaryEntityId;

                    UpdateRequest updatecountreq = new UpdateRequest()
                    {
                        Target = incidentEntity,
                    };
                    UpdateResponse res = (UpdateResponse)service.Execute(updatecountreq);
                  
                }

            }
            catch (Exception ex)
            {
                //Helpers.Throw(String.Format("An error occurred in the {0} workflow.",
                //        this.GetType().ToString()),
                //      ex);
                throw new InvalidPluginExecutionException("An error occurred in the plug-in.  " , ex);
            }
        }
        #region Input Parameters

        [Input("new_days")]
        [ReferenceTarget("salesorder")]
        public InArgument<int> InvoiceTimes { get; set; }

        [Input("new_nextinvoice")]
        [ReferenceTarget("salesorder")]
        public InArgument<int> InvoiceDate { get; set; }

        #endregion


    }
}

need to give the reference:

System.runtime.serializer.

then we need to attach it for debug:

1. take the dll and pdb to the server: dynamiccrm\server\bin\assembly
2. run the asynchronous services in service.msc
3. in x64  MSVSMON.exe, run as administrator and give permissions.
4. copy the server name in x64 MSVSMON.exe
5. register the dll in plugin register tool.
6. select all process in attachment dialogue box.
7. select CRMAsychonos.exe and attach it to process.


Tuesday 12 June 2012

Some work arrounds in dynamic crm 2011

Import the Excel file to crm.

go to Settings-->Data Management--> import.

click on Import Database.

you will have to upload only the .csv files.



here we can choose the automatic mapping or the Contact and Account data at  a time.

Next map the field























check  the duplicates






















then you will get the data from the excel to crm

Monday 11 June 2012

Entity in another entity record in dynamic crm 2011

Senario:

ex: opportunity and opportunity product

look like here we need to give new_Subcooldrink entity in the form of new_Cooldrink entity

for this first we need to create new_Cooldrink entity

after that create new_subcooldrink  enity.
here we need  not to give the display area.

save it and give the required attributes

give the N:1 relation ship from

new_subcooldrink to new_cooldrink 


then customize the cooldrink form. Insert  the Sub Grid