Wednesday 25 July 2012

create 3d charts

For creating 3D charts:
1. create chart
2. export chat
3. open in visual studio.
4. give the <Area3DStyle Enable3D=True">
in 


</AxisX>
<Area3DStyle Enable3D="True" LightStyle="Realistic"  WallWidth="5" IsRightAngleAxes="true" />
 
</ChartArea>



5. then import it.


check the links
http://niiranen.eu/crm/2010/10/turn-the-flat-dynamics-crm-2011-charts-into-3d/


imp link:
http://ms-crm-2011-beta.blogspot.in/2011/04/how-to-pass-parameters-from-one-plugin.html



PF information

How to get new PF region numbers:
http://59.180.233.229/estt_search/est_search.php

here we will give the establishment code:
for ex: Old pf account number:

KN/46294/21199

in this KN is region.

46294 is establishment code
 21199 is account number.

in above like check the establishment code.
you will get the new code.

like : PY/BOM, office details.

then go to below link:
http://epfoservices.in/epfo/member_balance/member_balance_office_select.php

here select the state.
click on search for establish code.

below you will get the office details.

select your office and give your account details.
PY/BOM/46294 /   /21199

name and mobile number. you will get the balance amount.





Monday 23 July 2012

update the child entity record

Senario

if we need to update a actual date field in Opportunityproduct entity with opportunity entity actual date field data.

here we need to give a field level mapping from opportunity to opportunityproduct.

other wise we need to write a plug in for create a record in opportunity product also.

create a record in opportunity product.


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.Actual.Est.dates
{
    public class Opportunitycreate:IPlugin
    {
        public DateTime actualdate;
        public DateTime estimateddate;

        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 != "new_opportunityitproduct")
                {
                    return;
                }
            }
            else
            {
                return;
            }

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

                Entity entity1 = (Entity)context.InputParameters["Target"];

                if (context.MessageName == "Create")
                {
                    //Money priceamt = (Money)entity1["new_price"];

                    //int timeonitems = Convert.ToInt32(entity1["estimatedvalue"]);
                    EntityReference var1 = (EntityReference)entity1["new_opportunityid"];


                    ColumnSet cols = new ColumnSet(true);

                    var contact1 = service.Retrieve("opportunity", var1.Id, cols);

                    if (contact1.Attributes.Keys.Contains("actualclosedate") == false)
                    {
                        //totalestrevenue = priceamt;
                        entity1["new_actualclosedate"] = null;

                        //actualdate = new DateTime();
                    }


                    else
                    {
                        // int timeofitems = Convert.ToInt32(contact1["new_price"]);
                        //Money estimatedamt = (Money)contact1["estimatedvalue"]; //

                        actualdate = (DateTime)contact1["actualclosedate"];

                        // totaltime = timeofitems + timeonitems;

                       // totalestrevenue = new Money() { Value = (estimatedamt.Value + priceamt.Value) };//estimatedamt + priceamt;
                    }

                    if (contact1.Attributes.Keys.Contains("estimatedclosedate") == false)
                    {

                        entity1["new_estimatedclosedate"] = null;
                    }
                    else
                    {
                        estimateddate = (DateTime)contact1["estimatedclosedate"];
                    }

                    if (actualdate == null && estimateddate == null)
                    {
                        service.Update(entity1);
                    }

                   // contact1["estimatedvalue"] = totalestrevenue;
                    if (actualdate != null)
                    {
                        if (actualdate.ToShortDateString() != "1/1/0001")
                        {
                            entity1["new_actualclosedate"] = actualdate;
                        }
                    }
                    else
                    {
                        entity1["new_actualclosedate"] = null;
                    }
                    if (estimateddate != null)
                    {
                        if (estimateddate.ToShortDateString() != "1/1/0001")
                        {
                            entity1["new_estimatedclosedate"] = estimateddate;
                        }
                    }

                    else
                    {
                        entity1["new_estimatedclosedate"] = null;
                    }
                  
                    service.Update(entity1);
                }




            }

            catch (FaultException<OrganizationServiceFault> ex)
            {
                throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
            }

        }

    }
}

Update a record in Opportunity:

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.Actual.Est.dates
{
   public class dateonupdate:IPlugin
    {
        public Nullable<DateTime> actualdate1;
        public Nullable<DateTime> estimateddate1; 

        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)
            {
                if (context.Depth > 1)
                {
                    return;
                }

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

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

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

                Entity entity1 = (Entity)context.InputParameters["Target"];

                

                string fetchquery = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
  "<entity name='new_opportunityitproduct'>" +
    "<attribute name='new_opportunityitproductid' />" +
    "<attribute name='new_name' />" +
    "<attribute name='new_category' />" +
    "<attribute name='new_subcategory' />" +
    "<attribute name='new_productservice' />" +
    "<attribute name='new_price' />" +
    "<attribute name='new_actualclosedate' />" +
    "<attribute name='new_estimatedclosedate' />" +
    "<attribute name='createdon' />" +
    "<order attribute='new_name' descending='false' />" +
    "<filter type='and'>" +
      "<condition attribute='new_opportunityid' operator='eq' uitype='opportunity' value='" + entity1.Id + "' />" +
    "</filter>" +
  "</entity>" +
"</fetch>";

                RetrieveMultipleRequest req = new RetrieveMultipleRequest();
                FetchExpression fetch = new FetchExpression(fetchquery);
                req.Query = fetch;
                RetrieveMultipleResponse resp = (RetrieveMultipleResponse)service.Execute(req);

                //oipt.Id = leadids;

                EntityCollection col = resp.EntityCollection;
                EntityReference opp = new EntityReference();
                opp.Id = entity.Id;
                opp.LogicalName = entity.LogicalName;

                Entity opp_product = new Entity();
                opp_product.LogicalName = "new_opportunityitproduct";

                if (entity1.Attributes.Keys.Contains("actualclosedate") == false)
                {
                    //actualdate1 = new System.DateTime();
                    //actualdate1 = DateTime.MinValue;
                    actualdate1 = null; 
                   
                }
                else
                {
                    actualdate1 = (DateTime)entity1["actualclosedate"];
                }



                if (entity1.Attributes.Keys.Contains("estimatedclosedate") == false)
                {
                    //estimateddate1 = DateTime.MinValue;

                    estimateddate1 = null;
                }
                else
                {
                    estimateddate1 = (DateTime)entity1["estimatedclosedate"];
                }
               

                foreach (var c in col.Entities)
                {
                    if (actualdate1 != null)
                    {

                        opp_product["new_actualclosedate"] = actualdate1;
                        //if (actualdate1.ToShortDateString() != "1/1/0001")
                        //{
                        //    opp_product["new_actualclosedate"] = actualdate1;
                        //}
                    }
                    if (estimateddate1 != null)
                    {

                        opp_product["new_estimatedclosedate"] = estimateddate1;
                        //if (estimateddate1.ToShortDateString() != "1/1/0001")
                        //{
                        //    opp_product["new_estimatedclosedate"] = estimateddate1;
                        //}
                    }
                    //opp_product["new_price"] = (Money)c["new_price"];//new Money() { Value = 0 };
                    //opp_product["new_opportunityid"] = 
                    opp_product.Id = c.Id;
                    opp_product.LogicalName = c.LogicalName;
                    service.Update(opp_product);
                    
                }           
                    
                
                

            }

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

        }

    }
}


Assign Date Field null:

Nullable<DateTime> actualdate1;
 actualdate1=null;
or  actualdate1.value=null;

Sunday 22 July 2012

combine lead, appointment,phone entities in SSRS.

senario:

if we need to get the data from Lead, Appointment, Phone Entities.


IF OBJECT_ID('tempdb..#AllReportees') IS NOT NULL
        DROP TABLE #AllReportees
        CREATE TABLE #AllReportees
(
    createdate Date,
    uname varchar(50),
    ownids uniqueidentifier,
    phoneact varchar(50),
    statuscode varchar(50)
  
)

INSERT INTO #AllReportees
select CONVERT(VARCHAR, createdon, 106) AS

date1,createdbyname,ownerid,activityid,statuscodename from FilteredPhoneCall
union
select CONVERT(VARCHAR, createdon, 106) AS

date1,createdbyname,ownerid,activityid,statuscodename from FilteredAppointment
union
select CONVERT(VARCHAR, createdon, 106) AS date1,createdbyname,ownerid,leadid,statuscodename

 from  FilteredLead



 select *
 ,dbo.Getwrongnumbercount(dd.createdate,dd.uname) as wrongcall
  from (
select  ss.createdate,ss.uname,
 count(distinct fp.activityid) as Phone ,
  count(distinct fl.leadid) as lead,
 (select count(*) from FilteredPhoneCall where  (CONVERT(VARCHAR, createdon, 106)=

ss.createdate) and (statuscodename = 'Wrong Number' or statuscodename = 'No Response')  )as

wrong,
   count(distinct fa.activityid) as appointment from #AllReportees ss
 left OUTER JOIN FilteredSystemUser AS su  WITH (NOLOCK) ON su.systemuserid=ss.ownids
 left OUTER JOIN  FilteredPhoneCall as fp WITH (NOLOCK) ON  (fp.activityid=ss.phoneact)
 left OUTER JOIN FilteredLead fl WITH (NOLOCK) ON  (fl.leadid=ss.phoneact)
 left OUTER JOIN FilteredAppointment AS fa WITH (NOLOCK) ON (fa.activityid=ss.phoneact)
  WHERE  (DATEPART(week, ss.createdate) = DATEPART(week, GETDATE()))   group by

ss.createdate,uname
     ) dd

creating a function in sql server 2008 r2

create a function in sql server:

take the Scalar-function.

Function:

create FUNCTION Getwrongnumbercount
(
-- Add the parameters for the function here
@createdate date,
@uname varchar(50)

)
RETURNS int
AS
BEGIN
-- Declare the return variable here
DECLARE
@ResultVar int

-- Add the T-SQL statements to compute the return value here
set @ResultVar = (select count(*) from FilteredPhoneCall where  (CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, createdon))) = @createdate) and (statuscodename = 'Wrong Number' or statuscodename = 'No Response') and (createdbyname = @uname ))

-- Return the result of the function
RETURN @ResultVar

END
GO

Wednesday 11 July 2012

using Fetch XML to retreive data from dynamic crm

Senario: need to retreive data in C#.net code from dynamic crm 2011.


public Stream SearchCaseByOwner(string owner, bool isAll)
        {
            string query = "<fetch mapping='logical'><entity name='incident'><attribute name='incidentid'/><attribute name='title'/><attribute name='ticketnumber'/><attribute name='customerid'/><attribute name='customeridname'/><attribute name='con_kontaktpersonid'/><attribute name='con_kontaktpersonidname'/><attribute name='con_sagstypeid'/><attribute name='con_sagstypeidname'/><attribute name='con_afregningsform'/><attribute name='con_afregningsformname'/><attribute name='con_sagsstatus'/><order attribute='con_sagsstatus'/><filter type='and'><condition attribute='owneridname' operator='like' value='%{search}%'/></filter></entity></fetch>";
            string result = crmService.Fetch(query.Replace("{search}", owner));
            return ConvertCaseJS(result);
        }


search user:


public Stream SearchUser(string name, string customer)
        {
            return LoadLookup("contact", "yomifullname", "contactid", name, customer);
        }


 public Stream SearchUser(string name,bool isLookup)
        {
            return LoadLookup("contact", "yomifullname","contactid", name, isLookup);
        }


Reading the Lookup id name:
private Entity GetLookup(Customer entLoup)
        {
            if (entLoup == null) return null;
            Entity ent = new Entity();
            ent.Id = entLoup.Value.ToString();
            ent.Name = entLoup.name;
            return ent;
        }

Getting the Current user:
string username = System.Web.HttpContext.Current.User.Identity.Name;


Advanced Find for Fetch XML in crm 2011

senario:

if we want to select all opportunity products relating to opportunity:
1. need to select the advanced find.
2. choose the opportunity product entity.
3. check the relation between opportunity and opp.product.
if the 1:N relation name is new_opportunityId and display name is :"opportunity".
in condition:
4. select the opportunity .
5. eqal
6. select the opportunity name.

we will get the Fetch XML like:


<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
- <entity name="new_opportunityitproduct">
  <attribute name="new_opportunityitproductid" />
  <attribute name="new_name" />
  <attribute name="createdon" />
  <order attribute="new_name" descending="false" />
- <filter type="and">
  <condition attribute="new_opportunityid" operator="eq" uiname="test dates" uitype="opportunity" value="{77470EB8-19CB-E111-9E1C-00155D000B45}" />
  </filter>
  </entity>
  </fetch>


if you want dynamically. remove the value and give the id like:

value="+leadids+"

but in the code we need to give it only single quotation.

In c# code we need give like this:

string fetchquery = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
  "<entity name='new_leaditproduct'>" +
    "<attribute name='new_leaditproductid' />" +
    "<attribute name='new_name' />" +
    "<attribute name='new_category' />" +
    "<attribute name='new_subcategory' />" +
    "<attribute name='new_productservice' />" +
    "<attribute name='createdon' />" +
    "<order attribute='new_name' descending='false' />" +
    "<filter type='and'>" +
      "<condition attribute='new_productid' operator='eq' uitype='lead' value='" + var1.Id + "' />" +
    "</filter>" +
  "</entity>" +
"</fetch>";

then read the fetch xml:

RetrieveMultipleRequest req = new RetrieveMultipleRequest();
                    FetchExpression fetch = new FetchExpression(fetchquery);
                    req.Query = fetch;
                    RetrieveMultipleResponse resp = (RetrieveMultipleResponse)service.Execute(req);

                    //oipt.Id = leadids;

                    EntityCollection col = resp.EntityCollection;

reading the values.

Entity opp_product = new Entity();
                    opp_product.LogicalName = "new_opportunityitproduct";
                    EntityReference opp = new EntityReference();
                    opp.Id = entity.Id;
                    opp.LogicalName = entity.LogicalName;

foreach (var c in col.Entities)
                    {
                        opp_product["new_category"] = (EntityReference)c["new_category"];
                        opp_product["new_subcategory"] = (EntityReference)c["new_subcategory"];
                        opp_product["new_productservice"] = (EntityReference)c["new_productservice"];
                        opp_product["new_price"] = new Money() { Value = 0 };
                        opp_product["new_opportunityid"] = (EntityReference)opp;
                        service.Create(opp_product);
                    }

Tuesday 10 July 2012

getting opportunity products relating to opportunity

Senario: 

we need to retrieve the Opportunity Products relating to opportunity. and update the fields in opportunity product entity.

first retrieve the opportunity products relating to the particular opportunity:


string fetchquery = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
  "<entity name='new_opportunityitproduct'>" +
    "<attribute name='new_opportunityitproductid' />" +
    "<attribute name='new_name' />" +
    "<attribute name='new_category' />" +
    "<attribute name='new_subcategory' />" +
    "<attribute name='new_productservice' />" +
    "<attribute name='new_price' />" +
    "<attribute name='new_actuvalclosedate' />" +
    "<attribute name='new_estclosedate' />" +
    "<attribute name='createdon' />" +
    "<order attribute='new_name' descending='false' />" +
    "<filter type='and'>" +
      "<condition attribute='new_opportunityid' operator='eq' uitype='opportunity' value='" + entity1.Id + "' />" +
    "</filter>" +
  "</entity>" +
"</fetch>";

here : condition attribute is the 1:N  relation between opportunity and opportunity product.

reading the Fetch xml data:


RetrieveMultipleRequest req = new RetrieveMultipleRequest();
                FetchExpression fetch = new FetchExpression(fetchquery);
                req.Query = fetch;
                RetrieveMultipleResponse resp = (RetrieveMultipleResponse)service.Execute(req);

                //oipt.Id = leadids;

                EntityCollection col = resp.EntityCollection;


Ex  Plugin:


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.Actual.Est.dates
{
   public class dateonupdate:IPlugin
    {
        public DateTime actualdate;
        public DateTime estimateddate;

        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)
            {
                if (context.Depth > 1)
                {
                    return;
                }

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

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

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

                Entity entity1 = (Entity)context.InputParameters["Target"];

                string fetchquery = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
  "<entity name='new_opportunityitproduct'>" +
    "<attribute name='new_opportunityitproductid' />" +
    "<attribute name='new_name' />" +
    "<attribute name='new_category' />" +
    "<attribute name='new_subcategory' />" +
    "<attribute name='new_productservice' />" +
    "<attribute name='new_price' />" +
    "<attribute name='new_actuvalclosedate' />" +
    "<attribute name='new_estclosedate' />" +
    "<attribute name='createdon' />" +
    "<order attribute='new_name' descending='false' />" +
    "<filter type='and'>" +
      "<condition attribute='new_opportunityid' operator='eq' uitype='opportunity' value='" + entity1.Id + "' />" +
    "</filter>" +
  "</entity>" +
"</fetch>";

                RetrieveMultipleRequest req = new RetrieveMultipleRequest();
                FetchExpression fetch = new FetchExpression(fetchquery);
                req.Query = fetch;
                RetrieveMultipleResponse resp = (RetrieveMultipleResponse)service.Execute(req);

                //oipt.Id = leadids;

                EntityCollection col = resp.EntityCollection;
                EntityReference opp = new EntityReference();
                opp.Id = entity.Id;
                opp.LogicalName = entity.LogicalName;

                Entity opp_product = new Entity();
                opp_product.LogicalName = "new_opportunityitproduct";

                if (entity1.Attributes.Keys.Contains("actualclosedate") == false)
                {
                  
                }


                else
                {                  

                    actualdate = (DateTime)entity1["actualclosedate"];

                  
                }

                if (entity1.Attributes.Keys.Contains("estimatedclosedate") == false)
                {


                }
                else
                {
                    estimateddate = (DateTime)entity1["estimatedclosedate"];
                }


                foreach (var c in col.Entities)
                {
                    opp_product["new_actuvalclosedate"] = actualdate;
                    opp_product["new_estclosedate"] = estimateddate;
                    //opp_product["new_price"] = (Money)c["new_price"];//new Money() { Value = 0 };
                    //opp_product["new_opportunityid"] =
                    opp_product.Id = c.Id;
                    opp_product.LogicalName = c.LogicalName;
                    service.Update(opp_product);
                }          
                  
              


            }

            catch (FaultException<OrganizationServiceFault> ex)
            {
                throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
            }

        }

    }
}






calculate a field based on child entity field values on update

this is for update message:

here we need to take pre and post images



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.Est.Revenue.Calculation
{
   public class Estrevenueonupdate : IPlugin
    {
        public Money totalestimatedamt;

        //public Entity entity1;

        public IOrganizationService service;
        public IPluginExecutionContext context;
        public Money preprice;
        public Money postprice;
        public EntityReference slaid;

        public void Execute(IServiceProvider serviceProvider)
        {


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

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

            //Entity entity;

            //EntityReference

            // 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)
            {

                if (context.PreEntityImages.Contains("new_opportunityitproduct") && context.PreEntityImages["new_opportunityitproduct"] is Entity)
                {

                    Entity slaitem = (Entity)context.PreEntityImages["new_opportunityitproduct"];
                 preprice = (Money)slaitem.Attributes["new_price"];
                    slaid = (EntityReference)slaitem.Attributes["new_opportunityid"];
                }
                if (context.PostEntityImages.Contains("new_opportunityitproduct") && context.PostEntityImages["new_opportunityitproduct"] is Entity)
                {
                    Entity slaitems = (Entity)context.PostEntityImages["new_opportunityitproduct"];
                    postprice = (Money)slaitems.Attributes["new_price"];

                }


                ColumnSet cols = new ColumnSet(new String[] { "estimatedvalue" });
                var contact1 = service.Retrieve("opportunity", slaid.Id, cols);

                Money estimatedamt = (Money)contact1["estimatedvalue"];

                Money updatedamt = new Money() { Value = (postprice.Value - preprice.Value) };

                totalestimatedamt = new Money() { Value = (estimatedamt.Value + updatedamt.Value ) };
                //int timeofitems = Convert.ToInt32(contact1["slk_maxtime"]);
                //totaltime = timeofitems + (time2 - time1);
                contact1["estimatedvalue"] = totalestimatedamt;//totaltime;
                service.Update(contact1);

            }

            else return;
        }
          


    }
}

calculate a field based on child entity field values on delete



This on delete message.

here we need to take the preimage.

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.Est.Revenue.Calculation
{
    public class Estrevenueondelete:IPlugin
    {

        public Money totalestimatedamt;

        //public Entity entity1;

        public IOrganizationService service;
        public IPluginExecutionContext context;

        public void Execute(IServiceProvider serviceProvider)
        {


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

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

            // 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 EntityReference)
            {

                if (context.PreEntityImages.Contains("new_opportunityitproduct") && context.PreEntityImages["new_opportunityitproduct"] is Entity)
                {

                    Entity slaitem = (Entity)context.PreEntityImages["new_opportunityitproduct"];
                    //int time = (int)slaitem.Attributes["slk_time"];
                    Money priceamt = (Money)slaitem.Attributes["new_price"];

                    EntityReference slaid = (EntityReference)slaitem.Attributes["new_opportunityid"];

                    ColumnSet cols = new ColumnSet(new String[] { "estimatedvalue" });
                    var contact1 = service.Retrieve("opportunity", slaid.Id, cols);

                    Money estimatedamt = (Money)contact1["estimatedvalue"];

                    totalestimatedamt = new Money() { Value = (estimatedamt.Value - priceamt.Value) };
                    //int timeofitems = Convert.ToInt32(contact1["slk_maxtime"]);
                    //totaltime = timeofitems - time;
                    contact1["estimatedvalue"] = totalestimatedamt;//totaltime;
                    service.Update(contact1);

                }
            }
            else return;
        }
    }
}

calculate a field based on child entity field values on create

Senario:

Price is a field in opportunity product. we need to update the Opportunity entity Est. Revenue field
with the price:

this is for create a record in opportunity product entity.


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.Est.Revenue.Calculation
{
    public class Estrevenueoncreate:IPlugin
    {
        public Money totalestrevenue;

        public Entity entity1;

        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 != "new_opportunityitproduct")
                {
                    return;
                }
            }
            else
            {
                return;
            }

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

                Entity entity1 = (Entity)context.InputParameters["Target"];
                if (context.MessageName == "Create")
                {
                    Money priceamt = (Money)entity1["new_price"];
                    //int timeonitems = Convert.ToInt32(entity1["estimatedvalue"]);
                    EntityReference var1 = (EntityReference)entity1["new_opportunityid"];


                    ColumnSet cols = new ColumnSet(
                                         new String[] { "estimatedvalue" });

                    var contact1 = service.Retrieve("opportunity", var1.Id, cols);

                    if (contact1.Attributes.Keys.Contains("estimatedvalue") == false)
                    {
                        totalestrevenue = priceamt;
                    }


                    else
                    {
                       // int timeofitems = Convert.ToInt32(contact1["new_price"]);
                        Money estimatedamt = (Money)contact1["estimatedvalue"]; //

                       // totaltime = timeofitems + timeonitems;

                        totalestrevenue = new Money() { Value = (estimatedamt.Value + priceamt.Value) };//estimatedamt + priceamt;
                    }

                    contact1["estimatedvalue"] = totalestrevenue;

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


        }


    }
}

convert lead product to opportunity product

Senario:

we need to convert the lead product as opportunity product:

Getting Fetch XML code:  goto Advanced find:select the query. and get the fetch xml.


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.ITProduct.leadtooppotunity
{
    public class leadtoopportunity : 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 != "opportunity")
                {
                    return;
                }
            }

            else
            {
                return;
            }

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

                //    Entity entity1 = (Entity)context.InputParameters["Target"];



                ColumnSet cols = new ColumnSet(true);

                var opportunityset = service.Retrieve("opportunity", entity.Id, cols);


                if (opportunityset.Attributes.Keys.Contains("originatingleadid") == false)
                {
                    return;

                }

                else
                {

                    EntityReference var1 = (EntityReference)opportunityset["originatingleadid"];                

                    string fetchquery = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
  "<entity name='new_leaditproduct'>" +
    "<attribute name='new_leaditproductid' />" +
    "<attribute name='new_name' />" +
    "<attribute name='new_category' />" +
    "<attribute name='new_subcategory' />" +
    "<attribute name='new_productservice' />" +
    "<attribute name='createdon' />" +
    "<order attribute='new_name' descending='false' />" +
    "<filter type='and'>" +
      "<condition attribute='new_productid' operator='eq' uitype='lead' value='" + var1.Id + "' />" +
    "</filter>" +
  "</entity>" +
"</fetch>";
                  

                    RetrieveMultipleRequest req = new RetrieveMultipleRequest();
                    FetchExpression fetch = new FetchExpression(fetchquery);
                    req.Query = fetch;
                    RetrieveMultipleResponse resp = (RetrieveMultipleResponse)service.Execute(req);

                    //oipt.Id = leadids;

                    EntityCollection col = resp.EntityCollection;
                    Entity opp_product = new Entity();
                    opp_product.LogicalName = "new_opportunityitproduct";
                    EntityReference opp = new EntityReference();
                    opp.Id = entity.Id;
                    opp.LogicalName = entity.LogicalName;
                    foreach (var c in col.Entities)
                    {
                        opp_product["new_category"] = (EntityReference)c["new_category"];
                        opp_product["new_subcategory"] = (EntityReference)c["new_subcategory"];
                        opp_product["new_productservice"] = (EntityReference)c["new_productservice"];
                        opp_product["new_price"] = new Money() { Value = 0 };
                        opp_product["new_opportunityid"] = (EntityReference)opp;
                        service.Create(opp_product);
                    }
                  
                }
            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                throw new InvalidPluginExecutionException("An error occurred in the plug-in.  " + ex.Message.ToString());

            }

        }




    }
}

convert opportunity products as order products in dynamic crm 2011

senario:

need to convert opportunity products as order products.


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.ITproduct.opportunitytoorder
{
    public class ITproductsfromopp : 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);

                //    Entity entity1 = (Entity)context.InputParameters["Target"];

                ColumnSet cols = new ColumnSet(true);


                var opportunityset = service.Retrieve("salesorder", entity.Id, cols);
//read the opportunity field value in order form


                if (opportunityset.Attributes.Keys.Contains("opportunityid") == false)
                {
                    return;

                }

                else
                {

                    EntityReference var1 = (EntityReference)opportunityset["opportunityid"];                  

                    string fetchquery = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
  "<entity name='new_opportunityitproduct'>" +
    "<attribute name='new_opportunityitproductid' />" +
    "<attribute name='new_name' />" +
    "<attribute name='new_category' />" +
    "<attribute name='new_subcategory' />" +
    "<attribute name='new_productservice' />" +
    "<attribute name='new_price' />" +
    "<attribute name='createdon' />" +
    "<order attribute='new_name' descending='false' />" +
    "<filter type='and'>" +
      "<condition attribute='new_opportunityid' operator='eq' uitype='opportunity' value='" + var1.Id + "' />" +
    "</filter>" +
  "</entity>" +
"</fetch>";

// in the query: condition attribute is 1:N relations ship name.

                    RetrieveMultipleRequest req = new RetrieveMultipleRequest();
                    FetchExpression fetch = new FetchExpression(fetchquery);
                    req.Query = fetch;
                    RetrieveMultipleResponse resp = (RetrieveMultipleResponse)service.Execute(req);

                    //oipt.Id = leadids;

                    EntityCollection col = resp.EntityCollection;
//we need to create a record in order product.

                    Entity opp_product = new Entity();
                    opp_product.LogicalName = "new_orderitproduct";
                    EntityReference opp = new EntityReference();
                    opp.Id = entity.Id;
                    opp.LogicalName = entity.LogicalName;
                    foreach (var c in col.Entities)
                    {
                        opp_product["new_category"] = (EntityReference)c["new_category"];
                        opp_product["new_subcategory"] = (EntityReference)c["new_subcategory"];
                        opp_product["new_productservice"] = (EntityReference)c["new_productservice"];
                        opp_product["new_price"] = (Money)c["new_price"];//new Money() { Value = 0 };
                        opp_product["new_orderid"] = (EntityReference)opp;
                        service.Create(opp_product);
                    }
                  


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

            }

        }


    }
}

Tuesday 3 July 2012

mobile number validate in dynamic crm 2011

for this refer:
http://blog.arkesystems.com/post/2011/06/22/Parsing-and-Validating-Phone-Numbers-in-CRM-2011.aspx

http://rudravarmabata.blogspot.in/2012/05/mobile-number-validation-using-regex.html


function validatePhone(context)
{
var phone =context.getEventSource().getValue();
var sTmp = phone.replace(/[^0-9]/g, "");
phoneRegex = /^\d{10}$/;
if( !sTmp.match( phoneRegex ) )
   {
   event.returnValue = false;
   alert("Phone must contain 10 numbers.") ;
   }
else
  {
   var sTmpClean =  "(" + sTmp.substr(0, 3) + ") " + sTmp.substr(3, 3) + "-" + sTmp.substr(6, 4);
   context.getEventSource().setValue(sTmpClean);
  }
}

give this javascript and check the field pass the parameters in onchage form.

two option set field customizations on java script on dynamic crm 2011

this is show how to use the two option set customizations on dynamic crm 2011


function businessregion()
{
var detailamt= Xrm.Page.getAttribute("new_businessregion").getValue();

if( detailamt==1)
{
Xrm.Page.ui.controls.get("new_state").setDisabled(true);
Xrm.Page.ui.controls.get("new_ther").setDisabled(false);

}

else
{
Xrm.Page.ui.controls.get("new_state").setDisabled(false);
Xrm.Page.ui.controls.get("new_ther").setDisabled(true);

}
}