Skip to main content

Microsoft Dynamics XRM proxies–Early bind in ASP.NET web service

 

As a hands on Development Manager I often get to lead by example, in my latest attempt to fast track re-development of some of our Java based web services to ASP.NET web service, I went about this using XRM based early bind method. I also explored SDK and JavaScript to execute the Dynamics rest API.

For a starter our web service methods roll up large datasets therefore JSON based service was obviously not suitable. Also the java based services made calls to multiple stored procedures through Hibernate frame work, the idea was to convert any calls to Dynamics CRM using XRM with LINQ and other bits and pieces using NHibernate framework.

I am keen to learn alternative methods and very open for feedback on the approach I have taken here.

Without further ado here are the steps.

 

1. Re-Compile XRM to include proxies for Dynamics CRM customisations. This was easily done by executing the following commands within the CrmSvcUtil.cmd file


REM $0\..\..\Microsoft.Xrm\bin\CrmSvcUtil /codeCustomization:"Microsoft.Xrm.Client.CodeGeneration.CodeCustomization, Microsoft.Xrm.Client.CodeGeneration" /out:Xrm\Xrm.cs /url:http://yourcrmurl/XRMServices/2011/Organization.svc /username:username@domain /password:userpassword /namespace:Xrm /serviceContextName:XrmServiceContext /serviceContextPrefix:Xrm
$0\..\..\Microsoft.Xrm\bin\CrmSvcUtil /codeCustomization:"Microsoft.Xrm.Client.CodeGeneration.CodeCustomization, Microsoft.Xrm.Client.CodeGeneration" /out:Xrm\Xrm.cs /url:http://yourcrmurl/YOURORG/XRMServices/2011/Organization.svc /domain:yourdomain /username:username /password:p: password /namespace:Xrm /serviceContextName:XrmServiceContext /serviceContextPrefix:Xrm

 

2. Create a ASP.NET web service project or WCF project in VS 2010 and references to XRM and SDK note the portal and the rest of the references are not required. For this  POC and  to keep things simple I have gone with ASP.NET web service.

image

3. Add a web service method which adds a contact record to your CRM when executed with valid data.

This web method takes some of the values for the contact record as argument and does some validations before generating new GUID and creating a new contact in the CRM. Valiation is done using LINQ to query CRM for existing records. On succesfull completion it returns a simple message too. Of course this is a work in progress and a number improvements can be made.

[WebMethod]
      public String createContact(String contactSalutation, String contactFirstName, String contactLastName, String contactEmail1, String contactEmail2, String contactEmail3, String contactPhone, String contactFax, String addressLine1,
                                     String addressLine2, String addressLine3, String city, String suburb, String stateProvince, String postalCode, String country,
                                     String contactGUID)
      {
        
         
          List<NominatingOrganisation> nomorgList = new List<NominatingOrganisation>();
          if (string.IsNullOrEmpty(contactEmail1) || string.IsNullOrEmpty(contactFirstName) || string.IsNullOrEmpty(contactLastName))
          {
              return "Email, Firstname and Lastname are required fields";
          }

          if (!string.IsNullOrEmpty(contactEmail1)) {
              var contacts = from @contact in XrmContext.ContactSet where @contact.EMailAddress1.Equals(contactEmail1) select @contact;
              if (contacts.ToList().Count > 0 ){
                  return "A contact with the email id already exists in the crm";
              }
          }
          bool create = false;
          if (string.IsNullOrEmpty(contactGUID))
          {
              create = true;
          }

          logger.Info("Inovoking createNewContact(String contactFirstName, service method with primaryContactEmail = " + contactEmail1);

          if (create)
          {
              try
                 {
                  XrmContext.ClearChanges();
                  var newContact = new Contact();
                  newContact.Salutation = contactSalutation;                 
                  newContact.EMailAddress1 = contactEmail1.Trim();
                  newContact.EMailAddress2 = contactEmail2;
                  newContact.EMailAddress3 = contactEmail3;

                  newContact.FirstName = contactFirstName;
                  newContact.LastName = contactLastName;
                  newContact.Telephone1 = contactPhone;
                  newContact.Fax = contactFax;
                  newContact.Address1_Line1 = addressLine1;
                  newContact.Address1_Line2 = addressLine2;
                  newContact.Address1_Line3 = addressLine3;
                  newContact.Address1_City = city;
                  newContact.Address1_StateOrProvince = stateProvince;
                  newContact.Address1_PostalCode = postalCode;
                  newContact.Address1_Country = country;
                  newContact.adx_systemuser_contact = getSAGlobalRecordOwner();
                  newContact.Adx_username = contactEmail1.Trim();
                  newContact.Adx_LogonEnabled = true;
                 
                  newContact.Id = Guid.NewGuid();

                  XrmContext.Detach(newContact);

                  XrmContext.AddObject(newContact);
                  XrmContext.SaveChanges();                 
              } catch (Exception ex) {
                  return ex.Message;
              }              
          }

          logger.Info("Completing getNominatingOrganisationByPrimaryContact(String primaryContactEmail) = " + contactEmail1);

          return "Contact successfully created";
      }

 

4. Query the CRM for a list of entries and return it as an array of objects. This is simple enough and self explanatory. LINQ through XRM context to get a collection of records then loop through and prepare a List to return to the caller.

[WebMethod]
public List<Sector> getAllSectors()
{
    logger.Info("Inovoking AllSectors()");

    int count = 0;
    var sectors = from @sector in XrmContext.sectorSet
                  where @sector.ParentSectorId == null orderby sector.name
                  select @sector;

    List<Sector> sectorList = new List<Sector>();
    foreach (var sector in sectors)
    {
        if (sector != null)
        {
            Sector sec = new Sector();
            sec.sectorName = (String)sector.name;
            sectorList.Add(sec);
            count++;
        }
    }

    logger.Info("Completing AllSectors() service request result count " + sectors.ToList().Count());
    return sectorList;
}

Comments

Popular posts from this blog

External Authentication providers for SharePoint 2010–(Oracle/Sun Directory as user stores)

External Authentication providers for SharePoint 2010: Thank you for continuing to read my blogs. It is a Sunday afternoon and the Roosters are leading Panthers 10 points to 6 in NRL, by the look of it, it has all the signs of turning into a one sided match in the second half. I thought I might write a blog about SharePoint and Single Sign On with Non-Microsoft Technologies. The Problem: Often Organisations would like to utilise their existing stack of technologies with SharePoint. This is due to the popularity of SharePoint as a platform to consolidate and provide a range of application services either to replace an existing set of tools or compliment an existing applications suite. We fall under the latter. I am working within a truly heterogeneous environment at the moment, the extranet applications are built on a mix of technologies such as OpenText Livelink for DMS, Java and JBPM for for workflow and front end portals, Sun Directory and Oracle for User data and other DB La
LEARNING TO FLY WITH WITH LEARN TO FLY - MELBOURNE   SEPTEMBER 5, 2018   LTF student Balendran Thavarajah has just successfully completed his first solo flight. We thought it would be a great idea to share his flight story, to show you that it is possible to juggle a busy professional and family life with your dream of learning to fly. LTF: YOU’RE CURRENTLY COMPLETING YOUR RPC – WHAT’S YOUR END GOAL WITH FLYING? Balendran: In the short term, I would like to complete my RPC with passenger and cross-country endorsements. Ultimately, I want to obtain a Private Pilot Licence. WHAT MADE YOU WANT TO LEARN HOW TO FLY? I was fascinated by planes and the idea of an aircraft moving through the air. As a kid, I wanted to be a fighter jet pilot but, growing up in Northern Sri Lanka during a prolonged civil war provided no such opportunities. After arriving in Australia, I realised that private aviation was not for the privileged alone. Last year,