domingo, 15 de septiembre de 2013

CRM 4.0 - Acceder al CRM desde un aspx con funcion de impersonacion


Conectar desde un aspx con o sin impersonación


1) Añadir al aspx las referencias web



using Microsoft.Crm.Sdk;
using Query = Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy;
using Disco;


2) Incluir la siguiente función


- Modificar la URL según intenciones (AD o SPLA en  token.AuthenticationType y en disco.Url),
- Si se accede por IFD en el (service.Credentials) poner DefaultCredentials


public CrmService GetCrmService(HttpContext context, string orgName)
    {
        using (new CrmImpersonator())
        {
            string UserName = "usuario";
            string Password = "password";
            string Domain = "dominio";
            //Get the server url from the registry
            string CRM_REG_DIRECTORY = @"software\Microsoft\mscrm\";
            RegistryKey regkey = Registry.LocalMachine.OpenSubKey(CRM_REG_DIRECTORY);
            string crmServerURL = regkey.GetValue("ServerUrl").ToString();
            CrmService service = null;
            CrmDiscoveryService disco = new CrmDiscoveryService();
            disco.Credentials = new NetworkCredential(UserName, Password, Domain);
           
           
            crmServerURL = @"http://127.0.0.1:5602/mscrmservices";
           
            disco.Url = String.Concat(crmServerURL, "/2007/ad/CrmDiscoveryService.asmx");
            RetrieveOrganizationsRequest OrgRequest = new RetrieveOrganizationsRequest();
            OrgRequest.Password = Password;
            OrgRequest.UserId = Domain + "\\" + UserName;
            RetrieveOrganizationsResponse OrgResponse = (RetrieveOrganizationsResponse)disco.Execute(OrgRequest);
            orgName = orgName.ToLower();
            foreach (OrganizationDetail OrgDetail in OrgResponse.OrganizationDetails)
            {
                if (OrgDetail.OrganizationName.ToLower().Equals(orgName))
                {
                    //Retrieve the ticket.
                    RetrieveCrmTicketRequest ticketRequest = new RetrieveCrmTicketRequest();
                    ticketRequest.OrganizationName = OrgDetail.OrganizationName;
                    ticketRequest.UserId = Domain + "\\" + UserName;
                    ticketRequest.Password = Password;
                    RetrieveCrmTicketResponse ticketResponse = (RetrieveCrmTicketResponse)disco.Execute(ticketRequest);
                    // Setup the Authentication Token
                    CrmAuthenticationToken token = CrmAuthenticationToken.ExtractCrmAuthenticationToken(context, OrgDetail.OrganizationName);
                    token.OrganizationName = OrgDetail.OrganizationName;
                    //token.AuthenticationType = AuthenticationType.Spla; //2
                    token.AuthenticationType = AuthenticationType.AD;
                    token.CrmTicket = ticketResponse.CrmTicket;
                    //Setup Service
                    service = new CrmService();
                    service.Url = OrgDetail.CrmServiceUrl;
                                       
                    service.Credentials = new System.Net.NetworkCredential(UserName, Password, Domain);
                  
                    service.CrmAuthenticationTokenValue = token;
                    break;
                }
            }
            return service;
        }
    }



3) Llamar a la funcion y utilizar el servicio



protected void Page_Load(object sender, EventArgs e)
    {
        string orgname;
       
        try
        {
            //Retrieve the Query String from the current URL
            if (Request.QueryString["orgname"] == null)
            {
                orgname = string.Empty;
            }
            else
            {
                //Query String
                string orgquerystring = Request.QueryString["orgname"].ToString();
                if (string.IsNullOrEmpty(orgquerystring))
                {
                    orgname = string.Empty;
                }
                else
                {
                    orgname = orgquerystring;
                }
            }

           
            CrmService service = GetCrmService(Context, orgname);
           
            systemuser usuario = new systemuser();
            usuario = (systemuser)service.Retrieve(EntityName.systemuser.ToString(), new Guid(Context.User.Identity.Name), new Query.AllColumns());
            if (usuario.domainname != null)
            {
                Response.Write(usuario.domainname);
                nombreusuario = usuario.domainname;
            }
        }
        catch (SoapException sx)
        {
            Response.Write(sx.Detail.OuterXml);
        }

...

No hay comentarios:

Publicar un comentario