Archive for the 'Development Fun' Category

Sharepoint webpart example for Microsoft CRM 4.0

In this example , i would like to display Microsoft CRM Opportunities (In Progress) in sharepoint as Pie chart and “Legends” with the help of  sharepoint webpart.

sharepoint3


I have two list which are having data from Microsoft CRM.

List<decimal>EstimatedRevenue = Revenu();

List<string> Customers = CrmCustomer();

I used the .Net 3.5 chart control to create the pie chart and I binded this data with the help of DataBindXY(xValue,YValue);

Chart1.Series[“Default”].Points.DataBindXY(Customers, EstimatedRevenue);

I added the “Legends” and then used the” LegendCellColumn” to add different columns. One can enable the 3D by simply

Chart2.ChartAreas[“ChartArea1”].Area3DStyle.Enable3D = true;

List<decimal> IDD = MyVal();
List<decimal> estimated = MyEstimatesharepoint
Advertisements

Example of Integration of Microsoft CRM with ERP system (Dynamic C5)

In this example , i would show the data from Microsoft Dynamic C5 in Microsoft CRM 4.0.  I will be doing it in few simple steps:

1. I have ASP.net page which is used to get the ID from Account through Request.QueryString method.

crm1

 2. I will be using “Account No” from Microsoft CRM to retrieve the data from Dynamic C5. In the left panel i have “C5 Integration” as Account Left Nav Bar item. When user clicks it , ASP.net page gets the data from ERP System.

It is simple “SQL Data Table” which is populated with the data from ERP  system while passing the “Account No”.

table1

3. If we select a row by clicking on “vælge” (select) then it will open the more detail about activities of Customer. Here i am passing the ID of one of the column in current row to get more detailed information.

detail

Or

more-details2

Custom fields in Custom workflow

By using custom workflow , i will make Auto-numbering in CRM 4.0 .

 

I have created a readonly field on Account entity” new_auto” to hold the “Guid” of

Account. As GUID is always unique , so there is no question about it being duplication. We can use prefix whatever we want.  As one can see AC- (GUID). I will use cutom workflow to obtain the GUID of entity when it is created and then update the entity with the prefix+ GUID.

 

 

 

 

 

using System;

using System.ComponentModel;

using System.ComponentModel.Design;

using System.Collections;

using System.Drawing;

using System.Workflow.ComponentModel.Compiler;

using System.Workflow.ComponentModel.Serialization;

using System.Workflow.ComponentModel;

using System.Workflow.ComponentModel.Design;

using System.Workflow.Runtime;

using System.Workflow.Activities;

using System.Workflow.Activities.Rules;

using Microsoft.Crm.Sdk;

using Microsoft.Crm.SdkTypeProxy;

using Microsoft.Crm.Workflow;

using Microsoft.Crm.Workflow.Activities;

using Microsoft.Crm.Sdk.Query;

 

namespace Number

{

      [CrmWorkflowActivity(“OneTest”, “AccountNumber”)]

 

    public partial class Activity1 : SequenceActivity

    {

 

        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)

        {

 

 

            IContextService contextService = (IContextService)executionContext.GetService(typeof(IContextService));

 

            IWorkflowContext context = contextService.Context;

 

      ICrmService crmService = context.CreateCrmService();

 

      WhoAmIRequest systemUserRequest = new WhoAmIRequest();

 

      WhoAmIResponse systemUser = (WhoAmIResponse)crmService.Execute(systemUserRequest);

 

      ColumnSet cols = new ColumnSet();

 //Getting the ID of entity which unqiue itself

 

      Guid guidID = new Guid(this.objectID.Value.ToString());

 

          // i am using “AC” before GUID.This field will hold the GUID of account

 

      string Number  = “AC-=” + guidID;

 

      TargetRetrieveAccount target = new TargetRetrieveAccount();

 

      target.EntityId = guidID;

      RetrieveRequest getAccount = new RetrieveRequest();

 

      getAccount.ReturnDynamicEntities = true;

 

      getAccount.Target = target;

 

      getAccount.ColumnSet = new AllColumns();

 

      RetrieveResponse retrieved = (RetrieveResponse)crmService.Execute(getAccount);

 

      DynamicEntity regardingAccount = (DynamicEntity)retrieved.BusinessEntity;

 //i am using custom field to hold the value of “GUID” .

 

      if (regardingAccount.Properties.Contains(“new_auto”))

      {

 

          regardingAccount.Properties[“new_auto”] = Number;

 

      }

 

      else

      {

 

          regardingAccount.Properties.Add(new StringProperty(“new_auto”, Number));

      }

 

         crmService.Update(regardingAccount);

 

     

           return ActivityExecutionStatus.Closed;

 

        }

 

 

        public static DependencyProperty objectIDProperty = DependencyProperty.Register(“objectID”, typeof(Lookup), typeof(Activity1));

 

 

 

        [CrmInput(” objectID”)]

 

       [CrmReferenceTarget(“account”)]

 

       // [CrmReferenceTarget(“automatic.crm.new_audit”)]

       // public.automatic.crm.Lookup

 

        public Lookup  objectID

        {

 

            get

            {

 

                return (Lookup)base.GetValue(objectIDProperty);

 

            }

 

            set

            {

 

                base.SetValue(objectIDProperty, value);

 

            }

        }

 

  }

}

Finally we need to publish the workflow using developer tool and then calling the assembly from workflow.

 

Example of CRM 4.0 Plugin

In this example , i will display the number of calls made to an account .Number of calls will display on an account as soon as Sales or marketing people complete the phone calls.
I will make a new read only field on account Form “Total number of calls(new_totalnumberofcalls)” as shown in below figure.

Figure “Call made to an account

Figure = Displaying Total number of calls

Plugin will be registered as ” SetStateDynamicEntity”.

Code :

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Query;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
namespace Microsoft.Crm.Sdk.UpdatingAccount

{

public class endless : IPlugin
{

// assigning default value for total number of calls
int NumberOfCalls= 1;
public void Execute(IPluginExecutionContext context)
{

if (context.PrimaryEntityName == EntityName.phonecall.ToString() && context.InputParameters.Properties.Contains(“EntityMoniker”) && context.InputParameters.Properties.Contains(“State”))

{

// I will get the current Phone call Id and its state
Guid PhoneCallId = ((Moniker)context.InputParameters.Properties[“EntityMoniker”]).Id;
PhoneCallState stateCode = (PhoneCallState)Enum.Parse(typeof(PhoneCallState), ((string)context.InputParameters.Properties[“State”]));

// Only update the regarding account ‘s field , if the phone call is “completed”
if (stateCode == PhoneCallState.Completed)

{

ICrmService service = context.CreateCrmService(false);
phonecall myphonecall = (phonecall)service.Retrieve(EntityName.phonecall.ToString(),
PhoneCallId, new AllColumns());
string regardingType = myphonecall.regardingobjectid.type;
Guid regardingId = myphonecall.regardingobjectid.Value;

// Invalid customer type. then return .
if (regardingType != EntityName.account.ToString())

{
return;
}
// Retrieve the Account’s traget field

TargetRetrieveAccount target = new TargetRetrieveAccount();
target.EntityId = regardingId;

RetrieveRequest getAccount = new RetrieveRequest(); getAccount.ReturnDynamicEntities = true;

getAccount.Target = target;
getAccount.ColumnSet = new AllColumns();

// Get the account

RetrieveResponse retrieved = (RetrieveResponse)service.Execute(getAccount);
DynamicEntity regardingAccount = (DynamicEntity)retrieved.BusinessEntity;
// If the “Total number of call” exists, update them ,otherwise set it
if (regardingAccount.Properties.Contains(“new_totalnumberofcalls”))
{
((CrmNumber)regardingAccount.Properties[“new_totalnumberofcalls”]).Value += NumberOfCalls;
}
else

{
regardingAccount.Properties.Add(new CrmNumberProperty(“new_totalnumberofcalls”, new CrmNumber(NumberOfCalls))); }
// Updateing

service.Update(regardingAccount);
} }
}
}
}

Example of Custom Workflow Activity (CRM 4.0)

In this example, I will use two dates fields and then calculate the number of days . This can be used for different scenarios. In this example, I will be using scenario like:

When a case is registered, there are different life cycle –Test, In development, In Production.
When technician chooses “In Production” from drop down list, java script populates the “end date” and then the custom workflow assembly will calculate the number of days between both dates.

We have two custom fields on case entity

1 = Case start date
2= Case end date

We would like to calculate the number of days for a given case. I will be using the existing integer(actualserviceunits) field on case form to hold the value .

Result = Case end date –Case start date

I would like to use CustomWorkflowActivity and my input parameters will be :

1 = Guidid of Case (I would like to retrieve the given case and then update it)
2 = Start date
3 = End date

Code :

using System;
using System.IO;
using System.Net;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;

using Microsoft.Crm.Workflow;
using Microsoft.Crm.Workflow.Activities;
using Microsoft.Crm.Sdk.Query;

namespace Updatingincident
{
[CrmWorkflowActivity(“updating incident”, “cal”)]

public partial class calculate : SequenceActivity
{
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
{

IContextService contextService = (IContextService)executionContext.GetService(typeof(IContextService));
IWorkflowContext context = contextService.Context;

ICrmService crmService = context.CreateCrmService();

WhoAmIRequest systemUserRequest = new WhoAmIRequest();
WhoAmIResponse systemUser = (WhoAmIResponse)crmService.Execute(systemUserRequest);

// using the GUID of current case

ColumnSet cols = new ColumnSet();
Guid guidID = new Guid(this.objectID.Value.ToString());

incident ret = (incident)crmService.Retrieve(EntityName.incident.ToString(), guidID, new AllColumns());

DateTime a = DateTime.Parse(this.startdate.date);

DateTime b = DateTime.Parse(this.enddate.date);

TimeSpan tid = b – a;

CrmNumber tes = new CrmNumber();
tes.Value = tid.Days;
// i will use existing field on CRM incident to hold the integer value.

ret.actualserviceunits = tes;

// updating the case entity
crmService.Update(reto);

return ActivityExecutionStatus.Closed;
}

// getting the id of case

public static DependencyProperty objectIDProperty = DependencyProperty.Register(“objectID”, typeof(Lookup), typeof(calculate));

[CrmInput(” objectID”)]
[CrmReferenceTarget(“incident”)]
public Lookup objectID
{
get
{
return (Lookup)base.GetValue(objectIDProperty);
}
set
{
base.SetValue(objectIDProperty, value);
}

}

// start date as input parameter

public static DependencyProperty startdateProperty = DependencyProperty.Register(“startdate”, typeof(CrmDateTime), typeof(calculate));

[CrmInput(” startdate”)]

public CrmDateTime startdate
{
get
{
return (CrmDateTime)base.GetValue(startdateProperty);
}
set
{
base.SetValue(startdateProperty, value);
}
}

// End date as input parameter

public static DependencyProperty enddateProperty = DependencyProperty.Register(“enddate”, typeof(CrmDateTime), typeof(calculate));

[CrmInput(” enddate”)]

public CrmDateTime enddate
{
get
{
return (CrmDateTime)base.GetValue(enddateProperty);
}
set
{
base.SetValue(enddateProperty, value);
}
}

}
}

Register the assembly

Now we need to register the Custom assembly as pulgin . I would be using plugin developer to register this assembly.

Synchronizing DataBase with CRM 3.0 (updating existing and creating new accounts)

I will be synchronizing existing Database with the existing CRM Accounts. I will compare the Accounts on the basis of “Name”. If the Names are same, accounts will be updated (otherwise new account will be created in the CRM system) .
I will create Console application and then schedule it for specified interval (for example , 2 hours , 4 hours ).
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Configuration;
using System.Web;
using System.Data.SqlClient;
using UpdateCRMhourlybasis.crm;
namespace UpdateCRMhourlybasis
{

class Program
{

static void Main(string[] args)
{

// Navn 1 and Navn will use for comparison purpose .

string navn1; // This will be the name of Account from CRM
string navn; // This will be the name of Account from Database

CrmService service = new CrmService();
service.Credentials System.Net.CredentialCache.DefaultCredentials;

// Connection to the database and retrieving “Accounts” column in .

SqlConnection con = new SqlConnection(@”Data Source=NP-1;Initial
Catalog=Emailing;Integrated Security=True”);

SqlDataAdapter thisAdapter = new SqlDataAdapter(“SELECT * FROM Accounts”, con);
DataSet thisDataSet = new DataSet();
thisAdapter.Fill(thisDataSet, “Accounts”);

try
{
foreach (DataRow theRow in thisDataSet.Tables[“Accounts”].Rows)
{
// I will be using few fields for update
// Now , i will make query to retrieve accounts with the specified fields, i wish to //update.

QueryExpression query = new QueryExpression();
query.EntityName = “account”;
ColumnSet columns = new ColumnSet();

// columns to retrieve
columns.Attributes = new string[] { “accountid”, “address1_city”,
“address1_country”, “address1_fax”, “address1_line1”, “name” };
query.ColumnSet = columns;
query.Criteria = new FilterExpression();
query.Criteria.FilterOperator = LogicalOperator.And;
ConditionExpression condition1 = new ConditionExpression();
condition1.AttributeName = “name”;
condition1.Operator = ConditionOperator.Equal;

// This query will retrieve the accounts from CRM, where “name” equals the name //in
//database —-AccountName

condition1.Values = new object[] { (theRow[“AccountName”].ToString()) };

query.Criteria.Conditions = new ConditionExpression[] { condition1 };
BusinessEntityCollection ret = service.RetrieveMultiple(query);

// as mentioned , “Navn” is Name of Accounts in Database
navn = (theRow[“AccountName”].ToString());

string city = (theRow[“City”].ToString());
string Emailing = (theRow[“Email”].ToString());
string Country = (theRow[“Country”].ToString());

for (int i = 0; i < ret.BusinessEntities.Length; i++)
{
//Retrieving all accounts , where name of Accounts in database equal the name in //CRM.
account aba1 = (account)ret.BusinessEntities[i];
aba1.name = (theRow[“AccountName”].ToString());
// assiging the name of accounts (from CRM) to Navn1
navn1 = aba1.name;

aba1.address1_city = (theRow[“City”].ToString());
aba1.address1_country = (theRow[“Country”].ToString());
aba1.address1_line1 = (theRow[“Address”].ToString());

aba1.address1_postalcode = (theRow[“PostalCode”].ToString());
service.Update(aba1);

}

// This part will create new accounts , if names in database do not match //with the name in CRM

if(navn !=navn1)

{
account k = new account();
k.name = navn;
k.address1_city = city;
k.address1_country = Country;
k.emailaddress1 = Emailing;
service.Create(k);

}

}
}
catch (System.Web.Services.Protocols.SoapException ex)
{
ex.InnerException.ToString();
}
}
}
}

comparing CRM DateTime with the Today’s date

I have an example field on CRM account “new_lastupdated”.It is having DateTime format.
I will compare itwith the today’s date. If both are equal then a certain action can take place.Such kind of situation can be required in workflow assembly.In this example , i will be passingt he ID of an existing account.

Guid AccountId = new Guid(“7CD689B6-258C-DC11-A70B-000C29C6C877”);

try

{

account myaccount = (account)service.Retrieve(EntityName.account.ToString(), AccountId, new AllColumns());

if (DateTime.Today == DateTime.Parse(myaccount.new_lastupdated.Value.ToString ()))

{

// just for the sake of example , i will add on day in (new_update) date.

myaccount.new_lastupdated.Value = DateTime.Now.AddDays(1).ToString();

service.Update(myaccount);

}

}

catch (System.Web.Services.Protocols.SoapException ex)

{

ex.InnerException.ToString();

}