25 Şubat 2013 Pazartesi

CRM 4.0 - CRM SERVISE BAGLANMA ve BUSINESS ENTITY COLLECTION KULLANIMI



using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Services;
using System.Net;
using System.Configuration;
using MSDynamicsCRMHelper.CrmSdk;
using MSDynamicsCRMHelper.crmDisc;

namespace MSDynamicsCRMHelper
{
    class CRMHelper
    {
        public CrmService GetCRMService()
        {
            string _hostname = "crm";
            string _port = "5555";
            string orgname = "organization";
            DataAccess objDataAccess = new DataAccess();

            _hostname = objDataAccess.GetMessage("crmHost");
            _port = objDataAccess.GetMessage("crmPort");
            orgname = objDataAccess.GetMessage("crmOrg");
           
            CrmService service = new CrmService();

            string strCRMAuthenticationType = ConfigurationManager.AppSettings.Get("CRMAuthenticationType");
            if (strCRMAuthenticationType == "0")
            {
                service = GetOnPremiseCRMService(_hostname,_port,orgname);
            }
            else if (strCRMAuthenticationType == "2")
            {
                service = GetHostedCRMService(_port,orgname);
            }

            return service;
        }


        public CrmService GetOnPremiseCRMService( string _hostname ,string _port ,string orgname )
        {
            //Retrieve the organization name from the query string.
            CrmDiscoveryService disco = new CrmDiscoveryService();
            disco.Url = String.Format("http://{0}:{1}/MSCRMServices/2007/{2}/CrmDiscoveryService.asmx", _hostname, _port, "AD");

            disco.Credentials = new NetworkCredential("username", "password", "domain");
            //Retrieve a list of available organizations from the CrmDiscoveryService Web service.
            RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
            // Substitute an appropriate domain, username, and password here.

            orgRequest.UserId = "domain" + "\\" + "username";
            orgRequest.Password = "password";
            RetrieveOrganizationsResponse orgResponse = (RetrieveOrganizationsResponse)disco.Execute(orgRequest);
            //Find the target organization.
            OrganizationDetail orgInfo = null;

            foreach (OrganizationDetail orgdetail in orgResponse.OrganizationDetails)
            {
                if (orgdetail.OrganizationName.Equals(orgname))
                {
                    orgInfo = orgdetail;
                    break;
                }
            }

            // Check whether a matching organization was not found.
            if (orgInfo == null)
                throw new Exception("The specified organization was not found.");

            //Create the CrmService Web service proxy.
            CrmAuthenticationToken sdktoken = new CrmAuthenticationToken();
            sdktoken.AuthenticationType = 0;
            sdktoken.OrganizationName = orgInfo.OrganizationName;


            CrmService service = new CrmService();
            service.CrmAuthenticationTokenValue = sdktoken;
            service.Url = orgInfo.CrmServiceUrl;
            service.Credentials = new NetworkCredential("username", "password", "domain");
            return service;
        }

        public CrmService GetHostedCRMService(string _port, string orgname)
        {           
            //Retrieve the organization name from the query string.
            CrmDiscoveryService disco = new CrmDiscoveryService();
            disco.Url = "http://" + orgname + ".mycrm.in:"+_port+"/MSCRMServices/2007/SPLA/CrmDiscoveryService.asmx";           
            disco.Credentials = new NetworkCredential("username", "password", "domain");
            //Retrieve a list of available organizations from the CrmDiscoveryService Web service.
            RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
            // Substitute an appropriate domain, username, and password here.

            orgRequest.UserId = "domain" + "\\" + "username";
            orgRequest.Password = "password";
            RetrieveOrganizationsResponse orgResponse = (RetrieveOrganizationsResponse)disco.Execute(orgRequest);
            //Find the target organization.
            OrganizationDetail orgInfo = null;

            foreach (OrganizationDetail orgdetail in orgResponse.OrganizationDetails)
            {
                if (orgdetail.OrganizationName.Equals(orgname))
                {
                    orgInfo = orgdetail;
                    break;
                }
            }

            // Check whether a matching organization was not found.
            if (orgInfo == null)
                throw new Exception("The specified organization was not found.");

            //Retrieve a CrmTicket from the CrmDiscoveryService Web service.
            RetrieveCrmTicketRequest ticketRequest = new RetrieveCrmTicketRequest();
            ticketRequest.OrganizationName = orgInfo.OrganizationName;
            ticketRequest.UserId = "domain" + "\\" + "username";
            ticketRequest.Password = "password";

            RetrieveCrmTicketResponse ticketResponse =
                (RetrieveCrmTicketResponse)disco.Execute(ticketRequest);

            //Create the CrmService Web service proxy.
            CrmAuthenticationToken sdktoken = new CrmAuthenticationToken();
            sdktoken.AuthenticationType = 2;
            sdktoken.OrganizationName = orgInfo.OrganizationName;
            sdktoken.CrmTicket = ticketResponse.CrmTicket;

            CrmService service = new CrmService();
            service.CrmAuthenticationTokenValue = sdktoken;
            service.Url = orgInfo.CrmServiceUrl;
            service.Credentials = new NetworkCredential("username", "password", "domain");
            return service;
        }

        public BusinessEntityCollection GetSearchedEntityResult(CrmService service, EntityName EntName, string[] SearchColumns, string searchAttributeName, object searchAttributevalue, ConditionOperator searchOperator)
        {
            ColumnSet columns = new ColumnSet();
            columns.Attributes = SearchColumns;
            // Create a ConditionExpression.
            ConditionExpression conditionPrincipal = new ConditionExpression();

            // Set the ConditionExpressions properties so that the condition is true when the

            conditionPrincipal.AttributeName = searchAttributeName;
            conditionPrincipal.Operator = searchOperator;
            conditionPrincipal.Values = new object[1];
            conditionPrincipal.Values[0] = searchAttributevalue;

            // Create the FilterExpression.
            FilterExpression filterPrincipal = new FilterExpression();

            // Set the properties of the FilterExpression.
            filterPrincipal.FilterOperator = LogicalOperator.And;
            filterPrincipal.Conditions = new ConditionExpression[] { conditionPrincipal };

            QueryExpression query = new QueryExpression();
            query.ColumnSet = columns;
            query.EntityName = EntName.ToString();
            query.Criteria = filterPrincipal;

            BusinessEntityCollection result = service.RetrieveMultiple(query);
            return result;
        }

        public BusinessEntityCollection GetSearchedEntityResultMultipleAttribute(CrmService service, EntityName EntName, string[] SearchColumns, string[] searchAttributeName, object[] searchAttributevalue, ConditionOperator[] searchOperator)
        {
            ColumnSet columns = new ColumnSet();
            columns.Attributes = SearchColumns;
            // Create a ConditionExpression.

            ConditionExpression[] SetOfConditions = new ConditionExpression[searchAttributeName.Length];
            for (int Count = 0; Count < searchAttributeName.Length; Count++)
            {
                ConditionExpression conditionPrincipal = new ConditionExpression();

                // Set the ConditionExpressions properties so that the condition is true when the

                conditionPrincipal.AttributeName = searchAttributeName[Count];
                conditionPrincipal.Operator = searchOperator[Count];
                conditionPrincipal.Values = new object[1];
                conditionPrincipal.Values[0] = searchAttributevalue[Count];
                SetOfConditions[Count] = conditionPrincipal;
            }

            // Create the FilterExpression.
            FilterExpression filterPrincipal = new FilterExpression();

            // Set the properties of the FilterExpression.
            filterPrincipal.FilterOperator = LogicalOperator.And;
            filterPrincipal.Conditions = SetOfConditions;

            QueryExpression query = new QueryExpression();
            query.ColumnSet = columns;
            query.EntityName = EntName.ToString();
            query.Criteria = filterPrincipal;
            BusinessEntityCollection result = service.RetrieveMultiple(query);
            return result;
        }

        public BusinessEntityCollection GetSearchedEntityResultMultipleAttribute(CrmService service, EntityName EntName, string[] SearchColumns, string[] searchAttributeName, object[] searchAttributevalue, ConditionOperator[] searchOperator, LogicalOperator logicalOperator)
        {
            ColumnSet columns = new ColumnSet();
            columns.Attributes = SearchColumns;
            // Create a ConditionExpression.

            ConditionExpression[] SetOfConditions = new ConditionExpression[searchAttributeName.Length];
            for (int Count = 0; Count < searchAttributeName.Length; Count++)
            {
                ConditionExpression conditionPrincipal = new ConditionExpression();

                // Set the ConditionExpressions properties so that the condition is true when the

                conditionPrincipal.AttributeName = searchAttributeName[Count];
                conditionPrincipal.Operator = searchOperator[Count];
                conditionPrincipal.Values = new object[1];
                conditionPrincipal.Values[0] = searchAttributevalue[Count];
                SetOfConditions[Count] = conditionPrincipal;

            }

            // Create the FilterExpression.
            FilterExpression filterPrincipal = new FilterExpression();

            // Set the properties of the FilterExpression.
            filterPrincipal.FilterOperator = logicalOperator;
            filterPrincipal.Conditions = SetOfConditions;

            QueryExpression query = new QueryExpression();
            query.ColumnSet = columns;
            query.EntityName = EntName.ToString();
            query.Criteria = filterPrincipal;
            BusinessEntityCollection result = service.RetrieveMultiple(query);
            return result;
        }
    }
}

CRM 4.0 JAVASCRIPT- FORM TİPLERİ


Create Formu
crmForm.FormType == 1

Var olan kayıdı update formu
crmForm.FormType == 2

Update yapılamayan form
crmForm.FormType == 3

Deactive olmus form
crmForm.FormType == 4

Quick Create Formu
crmForm.FormType == 5

Bulk Edit Form
crmForm.FormType == 6

Kayıdın unique id sini alma(Guid id)
crmForm.ObjectId

Entitinin tipini verir
crmForm.ObjectTypeCode

Entitinin adini verir
crmForm.ObjectTypeName

Form online mı?
crmForm.IsOnline==true

Formun üzerinde degişiklik olup olmadıgını verir
crmForm.IsDirty==true

22 Şubat 2013 Cuma

CRM 2011 JAVASCRIPT -ATTACHEVENT EKLEME (KeyDown,KeyUp)


Not:Aşagıdaki ornekte formdaki bir alana keydown ve keyup attacheventi eklenmiştir.
/*GokhanMentese Ornek Javascript*/
function Quote_OnLoad() {
    var formType = Xrm.Page.ui.getFormType();
    if (formType == 1) {
        /*Form Create Hali*/
    }
    else {

    }
/*Formdaki alana keydown , keyup ekleme*/
    Xrm.Page.getControl('new_fileexplanation')._control._element.attachEvent("onkeydown", addQuoteNameKeyDown);
    Xrm.Page.getControl('new_fileexplanation')._control._element.attachEvent("onkeyup", addQuoteNameKeyUp);
}

function addQuoteNameKeyDown() {
    return KeyDown("new_fileexplanation");
}
function addQuoteNameKeyUp() {
    return KeyUp("new_fileexplanation");
}


function KeyDown(field) {
    var e = window.event;

    if (e != null && e.keyCode != null) {
        if (KarakterGecerliMi(e)) {
            return true;
        }
        else {
            return false;
        }
    }
}
function KeyUp(field) {
    var e = window.event;

    if (e != null && e.keyCode != null) {
        if (KarakterGecerliMi(e)) {
            var fileExplanation = document.getElementById(field);
            var quote = Xrm.Page.getAttribute("name");
            var quoteName = quote.getValue();

            if (fileExplanation != null && fileExplanation != undefined) {
                var nameSecond = fileExplanation.value;
                if (quoteName.length >= 13) {
                    var nameFirst = quoteName.substring(0, 13);
                    nameSecond = nameSecond != null && nameSecond != "" ? "-" + nameSecond : "";
                    quote.setValue(nameFirst + nameSecond);
                }
            }
        }
    }
}

function KarakterGecerliMi(e) {
    if (e.keyCode != null) {
        return true;
    }
    else {
        return false;
    }
}


CRM 4.0 - PLUGİN YAZIMI


Örnek Kod

using System.Collections.Generic;
using System.Text;
using Microsoft.Crm.Sdk;
using Microsoft.Win32;
using OrnekPlugins.CrmSdk;
using System.Collections;
using System.IO;

namespace OrnekPlugins
{
    public class Plugins : IPlugin
    {
        public void Execute(IPluginExecutionContext context)
        {
            try
            {
                #region CRMSERVICE
                OrnekPlugins.CrmSdk.CrmService crmService = null;

                OrnekPlugins.CrmSdk.CrmAuthenticationToken token = new      OrnekPlugins.CrmSdk.CrmAuthenticationToken();
                token.AuthenticationType = 0;// Active Directory =0
                token.OrganizationName = "CRM";

                crmService = new  OrnekPlugins.CrmSdk.CrmService();
                // crmService.PreAuthenticate = true;
                crmService.UnsafeAuthenticatedConnectionSharing = true;
                crmService.Url = @"http://deneme/MSCrmServices/2007/CrmService.asmx";
                crmService.CrmAuthenticationTokenValue = token;
                crmService.CrmAuthenticationTokenValue.CallerId = context.UserId;
                crmService.UseDefaultCredentials = false;
                crmService.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                //ICrmService crmService = context.CreateCrmService(context.UserId);

                //WhoAmIRequest request = new WhoAmIRequest();
                //WhoAmIResponse response = (WhoAmIResponse)crmService.Execute(request);
                #endregion

                Microsoft.Crm.Sdk.DynamicEntity inputEntity = null;
                Guid _inputEntity = Guid.Empty;

                #region Kontroller
                if (!context.InputParameters.Contains("Target"))
                    return;
                if (string.IsNullOrEmpty(context.MessageName))
                    return;
                if (string.IsNullOrEmpty(context.PrimaryEntityName))
                    return;
                #endregion

                #region InputEntityId Alma
                if (context.MessageName.ToUpper().Equals("CREATE"))
                {
                    inputEntity = (Microsoft.Crm.Sdk.DynamicEntity)context.InputParameters["Target"];
                    if (inputEntity != null && inputEntity.Properties.Contains("accountid"))
                    {
                        _inputEntity = new Guid(context.OutputParameters.Properties["id"].ToString());
                    }
                }
                else if (context.MessageName.ToUpper().Equals("UPDATE"))
                {
                    inputEntity = (Microsoft.Crm.Sdk.DynamicEntity)context.InputParameters["Target"];
                    if (inputEntity != null)
                    {
                        Microsoft.Crm.Sdk.Key input = (Microsoft.Crm.Sdk.Key)inputEntity["accountid"];
                        if (input != null && input.Value != Guid.Empty)
                        {
                            _inputEntity = input.Value;
                        }
                    }
                }
                #endregion

                #region FullCode
                if (_inputEntity != Guid.Empty)
                {
                    if (crmService != null)
                    {
                        switch (context.PrimaryEntityName.ToLower())
                        {
                            case "account":
                                {
                                 /*Bu araya yapılacak işlem yazılacak*/
                                } break;
                            default:
                                break;
                        }
                    }
                    else
                    {
                        throw new InvalidPluginExecutionException("An error occurred in the Plugins plug-in.Crm connection is broken");
                    }
                }
                #endregion
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                throw new InvalidPluginExecutionException("An error occurred in the Plugins plug-in.", ex);
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException("An error occurred in the Plugins plug-in.", ex);
            }
        }
}
}

CRM 4.0 - QUERY EXPRESSION (Link Entity Kullanımı)


public static BusinessEntityCollection FiyatKarsilastirmaTalebiBolgeleriniGetir(CrmService crmservice, Guid fiyatkarsilastirmatalebiid)
    {
      try /*CodeLibrary00*/
      {
        ConditionExpression sart = new ConditionExpression() { AttributeName = "new_fiyatkarsilastirmatalebiid", Operator = ConditionOperator.Equal, Values = new object[] { fiyatkarsilastirmatalebiid } };
        LinkEntity link1 = new LinkEntity()
        {
          LinkFromEntityName = "new_bolge",
          LinkFromAttributeName = "new_bolgeid",
          LinkToEntityName = "new_new_fiyatkarsilastirmatalebi_new_bolge",
          LinkToAttributeName = "new_bolgeid"
        };

        LinkEntity link2 = new LinkEntity()
        {
          LinkFromEntityName = "new_new_fiyatkarsilastirmatalebi_new_bolge",
          LinkFromAttributeName = "new_fiyatkarsilastirmatalebiid",
          LinkToEntityName = "new_fiyatkarsilastirmatalebi",
          LinkToAttributeName = "new_fiyatkarsilastirmatalebiid",
          LinkCriteria = new FilterExpression()
          {
            FilterOperator = LogicalOperator.And,
            Conditions = new ConditionExpression[] { sart }
          }
        };

        link1.LinkEntities = new LinkEntity[] { link2 };

        QueryExpression query = new QueryExpression()
        {
          EntityName = "new_bolge",
          ColumnSet = new ColumnSet() { Attributes = new string[] { "new_bolgeid" } },
          LinkEntities = new LinkEntity[] { link1 }
        };

        BusinessEntityCollection businessEC = null;

        businessEC = crmservice.RetrieveMultiple(query);

        if (businessEC != null && businessEC.BusinessEntities != null)
        {
          if (businessEC.BusinessEntities.Length != 0)
            return businessEC;
          else
            return new BusinessEntityCollection();
        }
        else
        {
          return new BusinessEntityCollection();
        }

      }
      catch (Exception ex)
      {
        CodeLibrary.HataMesajiEkle(codeLibrary_Exceptions, "CodeLibrary00", ex.Message);
        return new BusinessEntityCollection();
      }
    }

CRM 4.0 - ALANA NULL DEGER SET ETME METOTLARI



Picklist
    public static Picklist PickListNull()
    {
      Picklist nullPicklist = new Picklist();
      nullPicklist.IsNull = true;
      nullPicklist.IsNullSpecified = true;

      return nullPicklist;
    }

Lookup
    public static Lookup LookUpNull()
    {
      Lookup nullLookup = new Lookup();
      nullLookup .IsNull = true;
      nullLookup .IsNullSpecified = true;
      return nullLookup ;
    }

CrmDecimal
    public static CrmDecimal DecimalNull()
    {
      CrmDecimal nullDecimal = new CrmDecimal();
      nullDecimal.IsNull = true;
      nullDecimal.IsNullSpecified = true;
      return nullDecimal;
    }


21 Şubat 2013 Perşembe

CRM 4.0 -PLUGININ MESAJ TİPİNE GÖRE ENTİTY GUID ID ALMA


Create”:
Guid instanceID = new Guid(context.OutputParameters.Properties["id"].ToString());

 “Update”:
Guid instanceID = (Guid)((Microsoft.Crm.Sdk.Key)((Microsoft.Crm.Sdk.DynamicEntity)context.InputParameters.Properties["Target"]).Properties[context.PrimaryEntityName + "id"]).Value;

 “SetState”:
Guid instanceID = new Guid(context.OutputParameters.Properties["id"].ToString()); 

 “Assign”:
Guid instanceID = vInstanceID = (Guid)((Microsoft.Crm.Sdk.Moniker)context.InputParameters.Properties["Target"]).Id;

Delete”:
instanceID = ((Microsoft.Crm.Sdk.Moniker)context.InputParameters.Properties["Target"]).Id;

 “Close”:
Guid instanceID = ((Microsoft.Crm.Sdk.Lookup)((Microsoft.Crm.Sdk.DynamicEntity)context.InputParameters.Properties["IncidentResolution"]).Properties[context.PrimaryEntityName + "id"]).Value;

 “Route”:
Guid instanceID = ((Microsoft.Crm.Sdk.Moniker)context.InputParameters.Properties["Target"]).Id;

 “SetStateDynamicEntity”:
Guid instanceID = ((Microsoft.Crm.Sdk.Moniker)context.InputParameters.Properties["EntityMoniker"]).Id;

CRM 4.0 -SAHİP ATAMA (OWNER ASSIGN)


public static void AssignEt(CrmService service, string entityname, Guid assignee, Guid targetid)
    {
      try
      {
        SecurityPrincipal sp = new SecurityPrincipal()
          {
            Type = SecurityPrincipalType.User,/*Eger takıma atama yapılacaksa SecurityPrincipalType.User */
            PrincipalId = assignee
          };

        AssignRequest assign = null;
        if (entityname.Trim().ToLower().Equals("account"))
        {
          TargetOwnedAccount account= new TargetOwnedAccount ()
          {
            EntityId = targetid
          };

          assign = new AssignRequest
          {
            Assignee = sp,
            Target = account
          };
        }
   
        if (assign != null)
          service.Execute(assign);
      }
      catch (Exception)
      {
      }
    }

1 Şubat 2013 Cuma

CRM 4.0 ve CRM 2011 - ÖNEK DEĞIŞTIRME


Varlık ve alan adlarının öneki new_ varsayılan değeri ile başlamaktadır. Crm 4.0′da aşağıdaki şekilde Ayarlar–>Yönetim–>Sistem Ayarlarından Özelleştirme tabından new_ yerine başlamasını istediğiniz öneki verebilirsiniz. Bu değişiklik tamamen arka tarafta kodlama yaparken kullanılan bölümdür. Ön yüzde herhangi bir değişikliğe neden olmaz. Mesela burada crm_ olarak değiştirelim.

Bu işlemi projeye başladığınızda ilk iş olarak yapmalısınız. Aksi taktirde açılan bazı custom alanlar new_ daha sonraki alanlar crm_ olarak oluşur. Bu da kodlama yaparken sürekli özelleştirme sayfasından alanların adlarına bakmaya neden olur. Standart bir yapı kurulmamış olur.

Crm 2011′de konumu biraz daha değişmiştir.