Thursday, September 11, 2008

Creating Records for Many to Many Relationship in MS CRM


Have you ever created Many to Many Relationship in MS CRM 4.0 ?

Use AssociateEntitiesRequest Class (CrmService)
Contains the data needed to add a link between two entity instances in a many-to-many relationship.
When you create Many to Many Relationship between two entities (system / Custom), MS CRM 4.0 creates New Table in MS CRM database. The name would be the "Relationship name" which you specified while creating Many to Many relationship.

Now, how do u associate a record to Entities?

Let's say, You have One "Entity: Contact" and other "Entity: New_CustomEntity".


Step 1: Create the record for first "Entity: Contact" (you will get a GUID for this record)

Step 2: Create the record for Second "Entity: New_CustomEntity" (you will get a GUID for this record)

Step 3: When you create Many to Many Relationship between two entities, you will specify "Relationship name" Eg: Contact_New_CustomEntity_ManyToMany

Step 4: Call below method and pass both the Entity Information with Relationship name. For more info see below example.


// Code Create Moniker for first Entity: Contact
Moniker Moniker1 = new Moniker();
Moniker1.Id = new Guid("SPECIFY GUID For the record");
Moniker1.Name = EntityName.contact.ToString();
 
// Code Create Moniker for second Entity: New_CustomEntity
Moniker Moniker2 = new Moniker();
Moniker2.Id = new Guid("SPECIFY GUID For the record");
Moniker2.Name = EntityName.New_CustomEntity.ToString();
 
string strManyToManyRelationshipName = "Contact_New_CustomEntity_ManyToMany"; 
 
if (ObjCrmHelper.AssociateManyToManyEntityRecords(Moniker1, Moniker2, strManyToManyRelationshipName))
MessageBox.Show("Associated Entities Record.");
else
MessageBox.Show("Error Occoured.");


//Method which will associate the records.
public bool AssociateManyToManyEntityRecords(Moniker Moniker1, Moniker Moniker2, string strEntityRelationshipName)
{
try
{
// Create an AssociateEntities request.
AssociateEntitiesRequest request = new AssociateEntitiesRequest();

        // Set the ID of Moniker1 to the ID of the lead.
request.Moniker1 = Moniker1;

        // Set the ID of Moniker2 to the ID of the contact.
request.Moniker2 = Moniker2;

        // Set the relationship name to associate on.
request.RelationshipName = strEntityRelationshipName;

        // Execute the request.
Service.Execute(request);

        return true;
}

    catch (SoapException ex)
{
return false;
}
}

/******************/
Happy Coding !!!!!!


Thursday, August 21, 2008

Create and Send Email Activity

You can easily craete and send an email activity in MS CRM 3.0 / 4.0.

If you experience "MS CRM 4.0: Generic SQL error 0x80044150" error, Please enable the impersonation in the web.config:

Here is the simple code to Create and Send Email Activity:

public bool CreateAndSendEmail(Lookup EmailFrom, Lookup EmailTo, string EmailSubject, string EmailDescription, Lookup RegardingObject)
{
    try
    {
        #region Create Email Object
 
            email ObjEmail = new email();
 
            if(EmailFrom != null)
            {
                activityparty ObjFrom = new activityparty();
                ObjFrom.partyid = EmailFrom;
                ObjEmail.from = new activityparty[] { ObjFrom };
            }
 
            activityparty ObjTo = new activityparty();
            ObjTo.partyid = EmailTo;
            ObjEmail.to = new activityparty[] { ObjTo };
 
            // Assign Subject
            ObjEmail.subject = EmailSubject;
 
            // Assign Description
            ObjEmail.description = EmailDescription;
 
            CrmSdk.CrmBoolean direction = new CrmSdk.CrmBoolean();
            direction.Value = true;
            ObjEmail.directioncode = direction;
 
            //Regarding Case
            if(RegardingObject != null)
                ObjEmail.regardingobjectid = RegardingObject;
 
            //Create Email
            try
            {
                Guid EmailGuid = Service.Create(ObjEmail);
 
                // Create a SendEmail request.
                SendEmailRequest emailRequest = new SendEmailRequest();
                emailRequest.EmailId = EmailGuid;
                emailRequest.TrackingToken = "";
                emailRequest.IssueSend = true;
 
                // Send the email message.
                SendEmailResponse emailResponse = (SendEmailResponse)Service.Execute(emailRequest);
 
                return true;
            }
 
            catch (SoapException)
            {
                return false;
            } 
 
        #endregion Create Email Object
    }
    
    catch (SoapException)
    {
        return false;
    }
}


Hope you find this code helpful.
Happy Coding.

Tuesday, August 12, 2008

Working with Null Values in MS CRM


When you update an entity instance there is a mechanism you can use to differentiate the absence of a value from a null value. To set an attribute value to null you must set both IsNull and IsNullSpecified to true. For attributes of type String, you must assign the value to String.Empty. This same mechanism is used when you create a query to find a null value.

Another option is to use the type helper code available in Microsoft.Crm.Sdk assembly and in the CRMHelpers classes.

Example

The following code example shows you how to create null instances of the various Microsoft Dynamics CRM attribute types.

CrmBoolean boolean = new CrmBoolean();
boolean.IsNull = true;
boolean.IsNullSpecified = true;
 
CrmDecimal dec = new CrmDecimal();
dec.IsNull = true;
dec.IsNullSpecified = true;
 
CrmFloat f = new CrmFloat();
f.IsNull = true;
f.IsNullSpecified = true;
 
CrmMoney money = new CrmMoney();
money.IsNull = true;
money.IsNullSpecified = true;
 
CrmNumber number = new CrmNumber();
number.IsNull = true;
number.IsNullSpecified = true;
 
Lookup lookup = new Lookup();
lookup.IsNull = true;
lookup.IsNullSpecified = true;
 
PickList list = new PickList();
list.IsNull = true;
list.IsNullSpecified = true;
 
Status status = new StatusV();
status.IsNull = true;
status.IsNullSpecified = true;
 
Owner owner = new Owner();
owner.IsNull = true;
owner.IsNullSpecified = true;
 


Example

The following code example shows you how to create null instances of the various Microsoft Dynamics CRM attribute types using the type helper classes.

CrmBoolean boolean = CrmBoolean.Null;
 
CrmDecimal dec = CrmDecimal.Null;
 
CrmFloat flt = CrmFloat.Null;
 
CrmMoney money = CrmMoney.Null;
 
CrmNumber number = CrmNumber.Null;
 
Lookup lookup = Lookup.Null;
 
Picklist list = Picklist.Null;
 
Status status = Status.Null;
 
Owner owner = Owner.Null;

Set Default Value to a Lookup Attribute using JavaScript


Below Example will set the Default Primary Contact ID for Account Entity.

if(crmForm.all.primarycontactid.DataValue == null)
{       
        //Create an array to set as the DataValue for the lookup control.

        var lookupData = new Array();

       //Create an Object add to the array.
        var lookupItem= new Object();
 
       //Set the id, typename, and name properties to the object.
        lookupItem.id = 'SPECIFY GUID of an Entity';
        lookupItem.typename = 'SPECIFY Entity Name';
        lookupItem.name = 'SPECIFY Attribute DISPLAY Value'; 
       // Add the object to the array.
          lookupData[0] = lookupItem; 
      // Set the value of the lookup field to the value of the array.
        crmForm.all.primarycontactid.DataValue = lookupData; 
} 

Thursday, August 7, 2008

Create Note and Assign to a Entity.


Sample code which will create a note and attach to the specified Entity (Specify Entity Name and GUID of the Entity Record)


CrmService service = GetCrmService("http://192.168.150.221:5555", "ORGANIZATION", "USERNAME", "PASSWORD", "DOMAIN");
 
annotation note = new annotation();
 
note.subject = "NOTE SUBJECT";
note.filename = @"schema.xsd";
note.mimetype = "text/html";
 
string encodedData = string.Empty;
using (FileStream fs = new FileStream(@"c:\schema.xsd", FileMode.Open, FileAccess.Read))
{
byte[] byteData = new byte[fs.Length];
fs.Read(byteData, 0, byteData.Length);
encodedData = System.Convert.ToBase64String(byteData);
}
note.documentbody = encodedData;
 
note.objectid = new Lookup();
note.objectid.type = "SPECIFY ENTITY_NAME";
note.objectid.Value = new Guid("F27A627B-DF1A-DD11-AEA5-0003FF90FBC7");
note.objecttypecode = new EntityNameReference();
note.objecttypecode.Value = "SPECIFY ENTITY_NAME";
 
Guid annotationId = service.Create(note); 


---- HERE you can Initialize CRM SERVICE Object.....

public static CrmService GetCrmService(string crmServerUrl, string organizationName, string userName, string password, string domain)
{
    // Get the CRM Users appointments
    // Setup the Authentication Token
    CrmAuthenticationToken token = new CrmAuthenticationToken();
    token.OrganizationName = organizationName;
 
    CrmService service = new CrmService();
 
    if (crmServerUrl != null &&
    crmServerUrl.Length > 0)
    {
        UriBuilder builder = new UriBuilder(crmServerUrl);
        builder.Path = "//MSCRMServices//2007//CrmService.asmx";
        service.Url = builder.Uri.ToString();
    }
 
    service.Credentials = new System.Net.NetworkCredential(userName, password, domain);
    service.CrmAuthenticationTokenValue = token;
 
    return service;
}


Happy Coding....