domingo, 15 de septiembre de 2013

CRM 4.0 - Picklist relacionados y limitados por rango (sacado de otro blog)

PICKLIST ET RELATIONSHIP
Clark [MVP CRM] posted on Wednesday, November 26, 2008 8:28 AM

Bonjour
J'ai trouvé ça à cet endroit :
https://community.dynamics.com/forums/t/6337.aspx
Je n'ai pas testé mais ça m'a l'air de pouvoir fonctionner.
Chained Picklist Sample
//Form on load event
var CRM_FORM_TYPE_CREATE = 1;
var CRM_FORM_TYPE_UPDATE = 2;
// Only enable the dynamic picklist on a Create or Update form.  Disabled
and
// read-only forms are not editable and so do not require dynamic picklists.
switch (crmForm.FormType)
{
case CRM_FORM_TYPE_CREATE:
case CRM_FORM_TYPE_UPDATE:
// Get a reference to the Sub-Industry picklist element for later use
var oSubIndustry = crmForm.all.new_subindustry;
// Cache the original picklist "Options" array in an "expando" on the
// element.  We will use this original list to dynamicly re-build the
picklist
// based on the Industry the user selects.
oSubIndustry.originalPicklistOptions = oSubIndustry.Options;
// If there is not an Industry selected, we just need to disable the
// Sub-Industry.  As soon as the user selects an Industry, we will
// re-enable the Sub-Industry picklist.
if (crmForm.all.new_industry.DataValue == null)
{
oSubIndustry.Disabled = true;
}
else
{
// There is a value already selected, we need to limit the available
options
// to what is valid for the currently selected Industry value.  The code
to
// do this already exists in the Industry Picklist's onchange event.  We
will
// re-use this code by manually firing the event.
new_industry_onchange0();
}
break;
}

// Get the Industry Element, since this code is re-used by the form's onload
event
// we can not rely on the event.srcElement to have the approriate element.
var oIndustry = crmForm.all.new_industry;
// Initialize the Sub-Industry indexes
var iStartIndex = -1;
var iEndIndex = -1;
// Depending on what the user selects in the Industry picklist, we will
select
// a range of options in the Sub-Industry picklist to display.
//
// For the purposes of this sample, it is assumed that the display text of
each
// Industry will be known and will not be localized.  We have also ordered
the
// options in the Sub-Industry picklist so that they are group sequentially
per
// Industry.  This allows the code to simply define start and stop
Sub-Industry
// indexes for each Industry.
switch (oIndustry.SelectedText)
{
case "Accounting":
iStartIndex = 1;
iEndIndex = 5;
break;
case "Consulting":
iStartIndex = 6;
iEndIndex = 10;
break;
}

//Picklist ONChange event
// Get a reference to the Sub-Industry picklist element for later use

var oSubIndustry = crmForm.all.new_subindustry;
// If the indexes where set, update the Sub-Industry picklist
if (iStartIndex > -1 && iEndIndex > -1)
{

// Create a new array, which will hold the new picklist options
var oTempArray = new Array();
// Initialize the index for the temp array
var iIndex = 0;
// Now loop through the original Sub-Industry options, pull out the
// requested options a copy them into the temporary array.

for (var i = iStartIndex; i <= iEndIndex; i++)
{
oTempArray[iIndex] = oSubIndustry.originalPicklistOptions[i];
iIndex++;
}
// Reset the Sub-Industry picklist with the new options
oSubIndustry.Options = oTempArray;

// Enable the Sub-Industry picklist for the user
oSubIndustry.Disabled = false;

}
else
{
// The user has selected an unsupported Industry or no Industry
oSubIndustry.DataValue = null;
oSubIndustry.Disabled = true;
}
23d2b4ff-9764-4a3c-a9db-2d3b634c3f67@x8g2000yqk.googlegroups.com...

Bonjour,
Je cherche à créer une liste déroulante dont les valeurs vont dépendre
d'une première liste
déroulante , par exemple Catégorie 1 : légume > catégorie 2 :
carottes , choux , etc..
Merci pour vos idées.
Ben

CRM 4.0 - Picklist multievaluado (de jianwang)


Crear un picklist multievaluado


crmForm.all.new_picklist.multiple = true;
/*   
 Checkbox style Multi-Select Picklist   
 author: Jim Wang @ January 2009   

http://jianwang.blogspot.com   
 */    
     

 // PL - the picklist attribute; PLV - used to save selected picklist values    
 var PL = crmForm.all.new_picklist;    
 var PLV = crmForm.all.new_picklistvalue;   
    
 if( PL != null && PLV != null ) {   
  
 PL.style.display = "none";   
 PLV.style.display = "none";  
                     window.document.all.new_picklistvalue_c.style.visibility = "hidden";
   
 // Create a DIV container
   
 var addDiv = document.createElement("<div style='overflow-y:auto; height:80px; border:1px #6699cc solid; background-color:#ffffff;' />");   
  PL.parentNode.appendChild(addDiv);   
 

  // Initialise checkbox controls  
  for( var i = 1; i < PL.options.length; i++ ) {   
 
  var pOption = PL.options[i]; 
  if( !IsChecked( pOption.text ) )  
 var addInput = document.createElement("<input type='checkbox' style='border:none;width:25px; align:left;' />" );   
else   
    var addInput = document.createElement("<input type='checkbox' checked='checked' style='border:none; width:25px; align:left;' />" );   
 var addLabel = document.createElement("<label />");   
   
 addLabel.innerText = pOption.text;   
   
    var addBr = document.createElement(""); //it's a 'br' flag   
  
  
 PL.nextSibling.appendChild(addInput);   
    PL.nextSibling.appendChild(addLabel);   
   
 PL.nextSibling.appendChild(addBr); 
 
  }  


  // Check if it is selected   
 
 function IsChecked( pText ) {  
  if(PLV.value != "") {   
 
   var PLVT = PLV.value.split("||");
  
   for( var i = 0; i < PLVT.length; i++ ) {
   
    if( PLVT[i] == pText )   
     return true;  
   }  
  }
   
  return false;
 
 }  
 

 // Save the selected text, this filed can also be used in Advanced Find
   
 crmForm.attachEvent( "onsave" , OnSave);
 
 function OnSave()  {   
  
   PLV.value = "";  
   var getInput = PL.nextSibling.getElementsByTagName("input");   
   
   
  for( var i = 0; i < getInput.length; i++ ) {   
    
     if( getInput[i].checked) {   
      PLV.value += getInput[i].nextSibling.innerText + "||";  
   }   
  }   
   
 } 

CRM 4.0 - Picklist en varios idiomas con el metadata



PickList en varios idiomas con el metadata


RetrieveAttributeRequest req;
            req = new RetrieveAttributeRequest();
            req.EntityLogicalName = "new_evento";
            req.LogicalName = "new_tipodeevento";
            req.RetrieveAsIfPublished = true;
            RetrieveAttributeResponse resp = crmMetaService.Execute(req) as RetrieveAttributeResponse;
            PicklistAttributeMetadata listData = resp.AttributeMetadata as PicklistAttributeMetadata;
           
            foreach (Option option in listData.Options) {
                for (int i = 0; i < option.Label.LocLabels.Length; i++) {
                    if (option.Label.LocLabels[i].Label.ToUpper() == "??") {

                    }
                }
            }

CRM 4.0 - Ver en un Iframe la vista de otra entidad

Ver código de una búsqueda


javascript:void( alert( advFind.FetchXml ))
javascript:alert(document.body.outerHTML)
javascript:alert(resultRender.outerHTML)


Ver código de una vista


javascript:alert(document.frames[1].location)



Código de ver vista en IFRAME de otra entidad


if(crmForm.FormType == 1)
{
document.all.IFRAME_Case.src="about:blank";
}
else
{
var navService;
navService= "nav_new_intermedia_new_final";
document.all.navService;

if (navService!= null)
{
var lookup= crmForm.new_intermediaid;
var id= lookup.DataValue[0].id;
var objectid= "{6EE80775-0949-DD11-9AA8-000C299B7642}";
objectid= id;
//this optional code hides the activity from the left navigation bar
//navService.style.display = "none";
document.all.IFRAME_Finales.src="/" + ORG_UNIQUE_NAME + "/userdefined/areas.aspx?oId=" + objectid + "&oType=" + "10001" + "&security=852023&tabSet=new_intermedia_new_final";
alert(document.all.IFRAME_Finales.src);
}
}

-------------------------------------------------------------
Go to Edit and click on “Find NEXT”.  The search criterion is “loadarea”. The first one found should be in a
<div> tag.  The “id=’this’” is the “nav” part to be used in the code.
-------------------------------------------------------------




Por Jim Wang:

CRM 4.0 IFrame: Show Advanced Find Result View


1. Build your Advanced Find query and save it, then copy the Shortcut.
2. Put a IFrame control on the Form, clear the "Restrict cross-frame scripting" checkbox.
3. Put the below code to the OnLoad() event, you need to change the IFRAME_view name and the iFrame.src (copy and paste from the step 1)

var iFrame = crmForm.all.IFRAME_view;
iFrame.src = SERVER_URL + "/advancedfind/advfind.aspx?etn=contact&QueryId=%7b3882F0FA-2B3A-DE11-BFB8-0018FE7F3A64%7d&ViewType=4230&AutoRun=True";
iFrame.attachEvent( "onreadystatechange" , Ready);
function Ready()
{
  var iDoc = iFrame.contentWindow.document;
  if(iDoc.getElementById("crmMenuBar") != null && iDoc.getElementById("btnBack") != null)
  {
    iDoc.getElementById("crmMenuBar").style.display = "none"; // hide the top menu bar
    iDoc.getElementById("btnBack").style.display = "none"; // hide the bottom BACK button
  }
}

CRM 4.0 IFrame: Show Entity's Associated View


It's a common requirement to show entity's associated view(1:N, N:N) in IFrame, the below code works for both 1:N and N:N relationship,
it also works on both On-Premise and IFD deployment. All you need to do is find out(IE Developer Toolbar) the ID of the associated link.
The 1:N relationship needs these parameters in the request URL: oId, oType, security, tabSet
The N:N relationship needs an extra parameter: roleOrd in the request URL, which has been involved in the code.

var navId = "nav_new_new_myentity_account";
if(document.getElementById(navId) != null)
{
  var tmp = document.getElementById(navId).onclick.toString();
  tmp = tmp.substring(tmp.indexOf("'")+1, tmp.indexOf(";"));
  var loadArea = tmp.substring(0, tmp.indexOf("'"));
  var roleOrd =  (tmp.indexOf("roleOrd") == -1) ? -1 : tmp.substring( tmp.indexOf("roleOrd"), tmp.lastIndexOf("'")).replace("\\x3d", "=");
  crmForm.all.IFRAME_view.src = (roleOrd == -1) ? GetFrameSrc(loadArea) : GetFrameSrc(loadArea) + "&" + roleOrd;
}
function GetFrameSrc(tabSet)
{
  if (crmForm.ObjectId != null)
  {
    var id = crmForm.ObjectId;
    var type = crmForm.ObjectTypeCode;
    var security = crmFormSubmit.crmFormSubmitSecurity.value;
    var path = document.location.pathname.substring(0, document.location.pathname.indexOf("edit.aspx")) + "areas.aspx?";
    return (path + "oId=" + id + "&oType=" + type + "&security=" + security + "&tabSet=" + tabSet);
  }
  else
  {
    return "about:blank";
  }
}

CRM 4.0 - Iframe de solo lectura

function OnIframeTestReady()
{
    //Override the onmousedown event
    crmForm.all.IFRAME_MyIframe.contentWindow.document.onmousedown = function(){
                alert("La ventana es de solo lectura");
                return false;
    };
}

crmForm.all.IFRAME_MyIframe.attachEvent( "onreadystatechange" , OnIframeTestReady );
crmForm.all.IFRAME_MyIframe.src = "../isv/myweb/default.aspx?so=JTX-05012-7SCRY";

CRM 4.0 - Editar el sitemap para incluir un dashboard


Editar el SiteMap para incluir un DashBoard


<SubArea Id="nav_dashboard" PassParams="1"
         Url="/isv/dashboard/dashboard.aspx" >
 <Titles>
  <Title LCID="1033" Title="Dashboard" />
 </Titles>
</SubArea>

El LCID cambiara de acuerdo al idima instalado!



Privilegios sobre un DashBoard


So, following our example from above the following could be inside the SiteMap:ç
Multiple privileges may be used as well.
<SubArea Id="new_location " Entity="new_location">
<Privilege Entity="new_location" Privilege="Write" />
</SubArea>

Here are the possible values from the SDK:

All
AllowQuickCampaign
Append
AppendTo
Assign
Create
Delete
Read
Share
Write

Here's an example with multiple privileges:

<SubArea Id="new_location " Entity="new_location">
<Privilege Entity="new_location" Privilege="Read,Write,Share" />
</SubArea>

And finally, get creative. Just because the area is for an entity doesn't mean that the privilege
has to be for the same entity.
Perhaps the Location entity should only show up to users who have rights to write
to the Knowledge Base. The following would be completely legit as well:

<SubArea Id="new_location " Entity="new_location">
<Privilege Entity="kbarticle" Privilege="Read,Write" />
</SubArea>

CRM 4.0 - Scroll en un dashboard

Scroll en un dashboard


Creas una página con un IFRAME donde src es la página que tenias en el dashboard, y
haces apuntar el dashboard al IFRAME.

<html>
<head>
<title>Untitled Page</title>
</head>
<body style="width:100%; height:100%; background-color:#d6e8ff; margin:3 3 3 3">
<iframe id="frm" src="http:/sb00m/FAQ/FAQ.htm" frameborder=0 height=100% width=100%></iframe>
</body>
</html>

CRM 4.0 - Sacar un fetch de una búsqueda avanzada

Using Advanced Find for FetchXML builder v4.0


Some time ago I have written an article about how to use the Advanced Find as FetchXML builder. Today I tried using the javascript:prompt() method on a CRM 4.0 deployment and found out that the code doesn't work anymore. This alert script does still work though.

javascript:alert(resultRender.FetchXml.value);

A slightly different code which might be easier to remember is:

javascript:alert(document.all.FetchXml.value);

With the popup selected you can press copy+c and paste the result in a notepad window.

CRM 4.0 - Evitar caracteres raros en los fetch

if (nombreOportunidadXML.LastIndexOf('&') != -1)
    nombreOportunidadXML = nombreOportunidadXML.Replace("&", "&#38;");

if (nombreOportunidadXML.LastIndexOf('\'') != -1)
    nombreOportunidadXML = nombreOportunidadXML.Replace("\'", "&#39;");

CRM 4.0 - Ejemplos de fetch

Fetch XML Examples


The following are examples of use of the QueryXML parameter. See also Fetch XML Schema.

Example 1

Return all attributes of the account entity where the owning user's last name equals the value crmlastname, first name equals the value crmfirstname, and nickname equals the value crmnickname.
 Copy Code
<fetch mapping='logical'>
   <entity name='account'><all-attributes/>
      <link-entity name='systemuser' to='owninguser'>
         <filter type='and'>
            <condition attribute = 'lastname' operator='eq'
                       value='crmlastname'/>
            <condition attribute='firstname' operator='eq'
                       value='crmfirstname'/>
            <condition attribute='nickname' operator='eq'
                       value='crmnickname'/>
         </filter>
      </link-entity>
   </entity>
</fetch>

Example 2

Return all attributes from the account entity for accounts created today.
 Copy Code
<fetch mapping='logical'>
   <entity name='account'><all-attributes/>
      <filter type='and'>
         <condition attribute = 'createdon' operator='today'/>
      </filter>
   </entity>
</fetch>

Example 3

Return name and accountid from all accounts created within the last seven days.
 Copy Code
<fetch mapping='logical'>
   <entity name='account'>
      <attribute name = 'name'/>
      <attribute name = 'accountid'/>
      <filter type='and'>
         <condition attribute = 'createdon' operator='last-seven-days'/>
      </filter>
   </entity>
</fetch>"

Example 4

Return contactid and birthdate from all contacts where the birth date is December 12, 2000 (time format YYYY-MM-DDTHH:MM:SSZ).
 Copy Code
<fetch mapping='logical'>
   <entity name='contact'>
      <attribute name = 'contactid'/>
      <attribute name = 'birthdate'/>
      <filter type='and'>
         <condition attribute = 'birthdate' operator='on'
                    value='2000-12-12T00:00:00Z'/>
      </filter>
   </entity>
</fetch>

Example 5

Return all attributes from accounts where the account name either starts with "a" or starts with "d".
 Copy Code
<fetch mapping='logical'>
   <entity name='account'><all-attributes/>
      <filter type='or'>
         <condition attribute = 'name' operator='like' value='a%'/>
         <condition attribute = 'name' operator='like' value='d%'/>
      </filter>
   </entity>
</fetch>

Example 6

Return name and accountid from all accounts where the name starts with either "a" or "x", or the name ends with "!".
 Copy Code
<fetch mapping='logical'>
   <entity name='account'>
      <attribute name = 'name'/>
      <attribute name = 'accountid'/>
      <filter type='or'>
         <condition attribute = 'name' operator='like' value='a%'/>
         <condition attribute = 'name' operator='like' value='x%'/>
         <condition attribute = 'name' operator='like' value='%!'/>
      </filter>
   </entity>
</fetch>

Example 7

Retrieve the ticker symbol of the account whose name is "My Account".
 Copy Code
<fetch mapping='logical'>
   <entity name='account'>
      <attribute name='tickersymbol' />
      <filter type='and'>
           <condition attribute='name' operator='eq' value='My Account' />
      </filter>
   </entity>
</fetch>

Example 8

Retrieve all leads that were created within the last seven days.
 Copy Code
<fetch mapping='logical'>
   <entity name='lead'>
      <all-attributes />
      <filter type='and'>
         <condition attribute='createdon' operator='last-seven-days' />
      </filter>
   </entity>
</fetch>

Example 9

Retrieve all contacts whose first name begins with "A" or last name ends with "Z". Sort the result set in ascending order by last name.
 Copy Code
<fetch mapping='logical'>
   <entity name='contact'>
      <attribute name='firstname' />
      <attribute name='lastname' />
      <filter type='or'>
         <condition attribute='firstname' operator='like' value='A%' />
         <condition attribute='lastname' operator='like' value='%Z' />
      </filter>
      <order attribute='lastname' descending='false' />
   </entity>
</fetch>

Example 10

Retrieve the number of users in the system.
 Copy Code
<fetch mapping='logical' aggregate='true'>
   <entity name='systemuser'>
      <attribute name='systemuserid' aggregate='count' alias='number' />
   </entity>
</fetch>

Example 11

Retrieve the first 10 account records created by user Jeff Smith in the last month.
 Copy Code
<fetch mapping='logical' page='1' count='10'>
   <entity name='account'>
      <all-attributes />
      <link-entity name='systemuser' to='createdby'>
            <filter type='and'>
                  <condition attribute='firstname'
                             operator='eq' value='Jeff' />
                  <condition attribute='lastname'
                             operator='eq' value='Smith' />
            </filter>
      </link-entity>
      <filter type='and'>
            <condition attribute='createdon' operator='last-month' />
      </filter>
   </entity>
</fetch>

Example 12 – Inner Joins Between Entities

Retrieves the name field on the Invoice entity. This query returns a maximum of one (1) record that matches criteria on Page 1 of the result set.
 Copy Code
<fetch mapping='logical' page='1' count='1'>
   <entity name='invoice'>
      <attribute name = 'name'/>
      <link-entity name='invoicedetail' to='invoiceid' from='invoiceid'>
      </link-entity>
      <filter type='and'>
         <condition attribute = 'accountid' operator='eq'
                    value='{7F901912-DD67-47B9-A5B3-B702B9F84680}'/>
      </filter>
      <link-entity name='account' to='accountid'>
      </link-entity>
      <filter type='and'>
         <condition attribute = 'name' operator='like' value='%order%'/>
      </filter>
   </entity>
</fetch>

Example 13 – Inner Joins Between Entities

Retrieves the name field on the Invoice entity. This query returns a maximum of 10 records that match the criteria on Page 1 of the result set.
 Copy Code
<fetch mapping='logical' page='1' count='10'>
   <entity name='invoice'>
      <attribute name = 'name'/>
      <link-entity name='invoicedetail' to='invoiceid' from='invoiceid'>
      </link-entity>
      <filter type='and'>
         <condition attribute = 'accountid' operator='eq'
                    value='{7F901912-DD67-47B9-A5B3-B702B9F84680}'/>
      </filter>
      <link-entity name='account' to='accountid'>
         <filter type='and'>
            <condition attribute = 'name' operator='like'
                       value='%Account%'/>
         </filter>
      </link-entity>
   </entity>
</fetch>

Example 14 – Using the OrderBy Clause

Retrieves all contacts whose first name begins with "A" or last name ends with "Z" and sorts the result set in ascending order by last name.
 Copy Code
<fetch mapping='logical'>
   <entity name='contact'>
      <attribute name='firstname' />
      <attribute name='lastname' />
      <filter type='or'>
         <condition attribute='firstname' operator='like' value='A%' />
         <condition attribute='lastname' operator='like' value='%Z' />
      </filter>
      <order attribute='lastname' descending='false' />
   </entity>
</fetch>

CRM 4.0 - Crear un fetch y convertirlo en un Query


CREAR UN FETCH Y CONVERTIRLO EN UN QUERY


     contact contacto = new contact();
            string fetch = @"<fetch mapping='logical'><entity name='account'><attribute name='accountid'/><filter type='and'><condition attribute = 'accountid' operator='like' value='%0B111D2-67F7-DD11-B67D-000C29F50BC0' /></filter></entity></fetch>";
            FetchXmlToQueryExpressionRequest fetchqueryreq = new FetchXmlToQueryExpressionRequest();
            fetchqueryreq.FetchXml = fetch;
            FetchXmlToQueryExpressionResponse qe = (FetchXmlToQueryExpressionResponse)crmService.Execute(fetchqueryreq);
            // Create the request.
            RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
            retrieve.Query = qe.Query;
     retrieve.ReturnDynamicEntities = true;
            // Execute the request.
            RetrieveMultipleResponse retrieved2 = (RetrieveMultipleResponse)crmService.Execute(retrieve);

            if(retrieved2.BusinessEntityCollection.BusinessEntities.Count>0 ){

            }

CRM 4.0 - Agregar el componente plantilla al editor de mail de QuickCampaign

Modificar un componente para añadirle un boton de plantilla


Insercion de este codigo en el EmailForm.aspx del Quick Campaign Form.

(Para quick campaign en emailForm.aspx al final del todo)
<%--Javi--%>
<script type = "text/javascript" language="javascript">
    var sp = "<td unselectable=''on''>";
    sp += " <div unselectable=''on''></div></td>";
    var t = document.getElementById("HTMLBAR");//get the toolbar
    var c = t.getElementsByTagName("TD")[23].outerHTML; //get the first btn
    var v = c.replace("cmd-unsubscribeLink.gif","cmd-insertField.gif"); //clone and change
    v = v.replace("Anular la suscripción ","Insertar Plantilla ");
    v = v.replace(" Anular la suscripción"," Insertar Plantilla");
    v = v.replace("UnsubscribeLink()","ApplyTempCampaign()");
    t.outerHTML = t.outerHTML.replace(c,v+sp+c); //recreate the toolbar
</script>
<%--Javi--%>


Se llama a la función ApplyTempCampaign()


En el onload() de email
ApplyTempCampaign = function (){
//debugger;
    var sUrl = prependOrgName("/_grid/cmds/dlg_bulkemail.aspx?bulkemail=false&objectTypeCode=2&objectId=8AB451FA-4DED-DD11-9AE9-000C29F50BC0");
    var sResponse = openStdDlg(sUrl, null, 600, 350);
    if (sResponse != null)
    {
        crmForm.all.description.InsertValue( sResponse.EmailBody );
        var sEmailSubject = crmForm.all.subject.DataValue;
        if( !IsNull( sEmailSubject ) && sEmailSubject.length > 0 )
        {
            if( !confirm(LOCID_EMAIL_REPLACE_SUBJECT) )
            {
                return;
            }
        }
        crmForm.all.subject.DataValue = CrmEncodeDecode.CrmHtmlDecode(sResponse.EmailSubject).substr(0, crmForm.all.subject.MaxLength);
    }
}
-------------------------------------------

CRM 4 - Trabajar con el campo ActivityParty en entidades dynamicas

First, I establish a DynamicEntity of the activityparty type:
DynamicEntity activityParty = new DynamicEntity("activityparty");


Then, I create a new LookupProperty for the partyid attribute of our new activityparty entity, and set it to our customerId variable:
LookupProperty partyProperty = new LookupProperty("partyid", new Lookup(EntityName.account.ToString(), customerId));
activityParty.Properties.Add(partyProperty);


Finally, I create a new DynamicEntityArrayProperty for the customers attribute of my Service Activity, and load our activityParty into it as a DynamicEntity array:
DynamicEntityArrayProperty customersProperty = new DynamicEntityArrayProperty("customers", new DynamicEntity[] { activityParty });
serviceActivity.Properties.Add(customersProperty);


---------------------------------------Ejemplo-----------------------------------------------

partyProperty = new LookupProperty("partyid", new Lookup(EntityName.systemuser.ToString(), new Guid("047D5926-3A79-DF11-A35E-005056A9638C")));
activityParty.Properties.Add(partyProperty);
usersProperty = new DynamicEntityArrayProperty("from", new DynamicEntity[] { activityParty });
email.Properties.Add(usersProperty);
activityParty = new DynamicEntity("activityparty");
fromProperty = new StringProperty("addressused", "a@a.es");
activityParty.Properties.Add(fromProperty);
usersProperty = new DynamicEntityArrayProperty("to", new DynamicEntity[] { activityParty });
email.Properties.Add(usersProperty);

CRM 4.0 - Acceder al texto de un email desde javascript

Acceder al texto de un email en javascript

crmForm.all.descriptionIFrame.onreadystatechange=fnStartInit;
function fnStartInit() { 
    //alert("frame state:" + crmForm.all.descriptionIFrame.readyState);
    var msg = crmForm.all.descriptionIFrame.contentWindow.document.body;
    //alert("innerHTML: " + msg.innerHTML);
    if (crmForm.all.descriptionIFrame.readyState=="loading")  {
               
        msg.innerHTML= msg.innerHTML.replace(/crm=false/gi,"crm=true"); 
        //alert("innerHTML: " + msg.innerHTML);
    }
}

CRM 4.0 - Adjuntar un fichero a un email

 //Cojo el fichero y lo atacheo en una tarea del tipo mail de CRM y lo envió
            email mail = new email();
            activityparty from = new activityparty();
            from.partyid = new Lookup();
            //Administrator GUID
            from.partyid.Value = new Guid("5B61411D-0147-DD11-BCB8-000C299FD622");
            from.partyid.type = EntityName.systemuser.ToString();
            mail.from = new activityparty[] { from };
            activityparty to = new activityparty();
            to.partyid = new Lookup();
            //Mario Robles GUID
            to.partyid.Value = new Guid("5279C129-9B47-DD11-9B3A-000C299FD622");
            to.partyid.type = EntityName.contact.ToString();
            mail.to = new activityparty[] { to };
            mail.subject = "Mail con documento mergeado" + System.DateTime.Now;
            mail.description = "Mail con documento mergeado" + System.DateTime.Now;
            CrmBoolean direccion = new CrmBoolean();
            direccion.Value = true;
            mail.directioncode = direccion;
            FileStream stream = File.OpenRead(@"C:\DocumentoMergeado.xml");
            byte[] byteData = new byte[stream.Length];
            stream.Read(byteData, 0, byteData.Length);
            string encodedData = System.Convert.ToBase64String(byteData);
            Guid mailguid = crmService.Create(mail);
            activitymimeattachment attachment = new activitymimeattachment();
            attachment.activityid = new Lookup();
            attachment.activityid.Value = mailguid;
            attachment.activityid.type = EntityName.email.ToString();
            attachment.attachmentnumber = new CrmNumber();
            attachment.attachmentnumber.Value = 1;
            attachment.filename = "DocumentoMergeado.xml";
            attachment.mimetype = "application/xml";
            attachment.subject = "DocumentoMergeado.xml";
            attachment.body = encodedData;
            Guid guidatachment = crmService.Create(attachment);
            activitymimeattachment attachmentCheck = (activitymimeattachment)crmService.Retrieve(EntityName.activitymimeattachment.ToString(), guidatachment, new AllColumns());

CRM 4.0 - Emails

Como enviar un email


SendEmailRequest req = new SendEmailRequest();
req.EmailId = mail.activityid.Value;
req.TrackingToken = "";
req.IssueSend = true;
SendEmailResponse res = (SendEmailResponse)crmService.Execute(req);


Enviar un email utilizando una plantilla



//Declaracion del email
email mail = new email();
contact contacto = new contact();

//Asignacion del from y el to
//Propietario del contacto
activityparty from = new activityparty();
from.partyid = new Lookup();
from.partyid.Value = new Guid(encargado.systemuserid.Value.ToString());
from.partyid.type = EntityName.systemuser.ToString();
mail.from = new activityparty[] { from };
activityparty to = new activityparty();
to.partyid = new Lookup();

//Contacto creado
to.partyid.Value = new Guid(contacto.contactid.Value.ToString());
to.partyid.type = EntityName.contact.ToString();
mail.to = new activityparty[] { to };

//Busqueda de la plantilla adecuada
email cuerpoMail = new email();

//Hace falta esto para instanciar la plantilla que se busca
InstantiateTemplateRequest cuerpo = new InstantiateTemplateRequest();

//Template cuerpo : evento presencial
cuerpo.ObjectId = ((Key)usuarioDinamico.Properties["systemuserid"]).Value;
cuerpo.ObjectType = EntityName.systemuser.ToString();

QueryByAttribute queryCuerpo = new QueryByAttribute();
ColumnSet colsPlantilla = new ColumnSet();
colsPlantilla.AddColumn("body");
colsPlantilla.AddColumn("subject");
queryCuerpo.ColumnSet = colsPlantilla;
queryCuerpo.EntityName = EntityName.template.ToString();
queryCuerpo.Attributes = new string[] { "title" };
queryCuerpo.Values = new object[] { "Mi plantilla" };
BusinessEntityCollection retrievedTemplate = crmService.RetrieveMultiple(queryCuerpo);

if (retrievedTemplate.BusinessEntities.Length > 0) {
 cuerpo.TemplateId = ((template)retrievedTemplate.BusinessEntities[0]).templateid.Value;

 mail.description = ((email)cuerpoResponse.BusinessEntityCollection.BusinessEntities[0]).description;
 mail.subject = ((email)cuerpoResponse.BusinessEntityCollection.BusinessEntities[0]).subject;

 //Sustitucion de variables o aplicamos la traducción
 cuerpoMail.description = cuerpoMail.description.Replace(NOMBRE_CONTACTO, contacto.firstname);

 //Traductor traductor = new Traductor(crmService, metadataService);

 //Asignacion del texto al email que voy a enviar
 mail.description += cuerpoMail.description;
  //mail.description = traductor.Traduce(mail.description, ((Key)nifDinamico.Properties["new_nifid"]).Value, '[', ']');

 //creo el mail
 Guid mailguid = crmService.Create(mail);

 //envió el mail creado
 SendEmailRequest req = new SendEmailRequest();
 req.EmailId = mailguid;
 req.TrackingToken = "";
 req.IssueSend = true;
 SendEmailResponse res = (SendEmailResponse)crmService.Execute(req);
}

CRM 4.0 - Uso del DateTime

Se convierten en DateTime y se aplica el Compare


Tipo de valor
 Condición

Menor que cero
 t1 es menor que t2.

Cero
 t1 es igual a t2.

Mayor que cero
 t1 es mayor que t2.



 public static int Compare (
 DateTime t1,
 DateTime t2
)

CRMDateTime To  DateTime


When working with CrmDateTime, you'll notice that this type does have a .value attribute,
but the type of this attribute is string. There is no attribute to get the .net class DateTime out of your CrmDateTime.
If you do want to use a DateTime anyway, you'd easily need to convert it. You could use any of these:

Convert.ToDateTime(crmdatetime.Value)
DateTime.Parse(crmdatetime.Value)

For more information on the CrmDateTime, look in the SDK:
http://msdn2.microsoft.com/en-us/library/aa613542.aspx


DateTime to CRMDateTime


static public CrmDateTime ConvertToCRMDateTime(DateTime dateTime) {
            CrmDateTime crmDateTime = new CrmDateTime();
            crmDateTime.date = dateTime.ToShortDateString();
            crmDateTime.time = dateTime.ToShortTimeString();
            TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset(dateTime);
            string sOffset = string.Empty;

            if (offset.Hours < 0) {
                sOffset = "-" + offset.ToString().Substring(1, 4);
            }
            else {
                sOffset = "+" + offset.ToString().Substring(0, 5);
            }
            //sOffset += offset.Minutes.ToString().PadLeft(2, '0');
            crmDateTime.Value = dateTime.ToString(string.Format("yyyy-MM-ddTHH:mm:ss{0}", sOffset));
            return crmDateTime;
        }

Uso de formato de fechas según cultura e idioma


DateTimeFormatInfo dfi = new DateTimeFormatInfo();
//CultureInfo ci = new CultureInfo("es-ES");
CultureInfo ci = new CultureInfo("en-US");

dfi.MonthDayPattern = "MM-MMMM, ddd-dddd";
DateTime time = new DateTime();
time = DateTime.Now;
       
Label1.Text = time.ToString("f",ci);

CRM 4.0 - Impersonación con aspx y SSL

using (new CrmImpersonator())
            {
                System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate(object senderx, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
...

}

CRM 4.0 - Impersonación en páginas aspx

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;
                }
            }

        //---------------------------------------

            using (new CrmImpersonator())
        {
            CrmAuthenticationToken token;
          
            token = CrmAuthenticationToken.ExtractCrmAuthenticationToken(Context, orgname);
           
            token.OrganizationName = orgname;
            token.AuthenticationType = 0;
            //Create the Service
            CrmService Crmservice = new CrmService();
            Crmservice.Credentials = System.Net.CredentialCache.DefaultCredentials;
            Crmservice.CrmAuthenticationTokenValue = token;
            string crmurl = @"http://127.0.0.1:5601/mscrmservices";
            Crmservice.Url = crmurl + "/2007/CrmService.asmx";
            account account = new account();
            account.name = "Offline Impersonator: " + DateTime.Now.TimeOfDay.ToString();
            systemuser usuario = new systemuser();
            usuario = (systemuser)Crmservice.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);
        }

    }

CRM 4.0 - Funcion GetCrmService

private CrmSdk.CrmService GetCrmService(string organizationName) {
            // Setup the Authentication Token
            CrmSdk.CrmAuthenticationToken token = new CrmAuthenticationToken();
            token.OrganizationName = organizationName;
            CrmSdk.CrmService crmService = new CrmSdk.CrmService();
            crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
            crmService.CrmAuthenticationTokenValue = token;
            return crmService;
        }

...

CrmService crmService = GetCrmService("organiacion");
crmService.Credentials = new System.Net.NetworkCredential("usuario", "pass", "domain");

.NET - Encriptación y almacenamiento de claves en web.config y registro windows

Identificación en ASP con password almacenada


1) Usando texto plano

<identity impersonate="true" userName="contoso\Jane" password="pass"/>


2) usando el registro de windows (aspnet_setreg)

userName="registry:HKLM\Software\AspNetIdentity,Name"
password="registry:HKLM\Software\AspNetIdentity,Password"
The credentials must be in REG_BINARY format, containing the output of a call to the Windows API function CryptProtectData. You can create the encrypted credentials and store them in the registry with the ASP.NET Set Registry console application(Aspnet_setreg.exe), which uses CryptProtectData to accomplish the encryption. To download Aspnet_setreg.exe, along with the Visual C++ source code and documentation, visit the Web site www.asp.net and search for "aspnet_setreg".
You should configure access to the key storing the encrypted credentials so that access is provided only to Administrators and SYSTEM. Because the key will be read by the ASP.NET process running as SYSTEM, you should set the following permissions:
Administrators:F
SYSTEM:F
CREATOR OWNER:F
ProcessAccount:R


3) Usando el web.config y encriptando la informacion de usuario y clave

The Aspnet_regiis.exe tool (located in the %SystemRoot%\Microsoft.NET\Framework\versionNumber folder)
includes options for encrypting and decrypting sections of a Web.config file, creating or deleting key containers, exporting and importing key container information, and managing access to a key container.
Once you have specified which provider to use, you can encrypt or decrypt the contents of the Web.config file for your application.

Use the –app option to identify the application for which the Web.config file will be encrypted and the -site option to identify which Web site the application is a part of. The Web site is identified using the site number from the Internet Information Services (IIS) metabase. You can retrieve the site number from the INSTANCE_META_PATH server variable in the ServerVariables collection. For example, when IIS is installed, a Web site named "Default Web Site" is created as site 1. In pages served from that site, the INSTANCE_META_PATH server variable returns "/LM/W3SVC/1". If you do not specify a -site option, site 1 is used.
To see all the possible server variables in IIS, place the following code into an Active Server Page, then browse to it:
<table BORDER="1">
<th COLSPAN="2">ServerVariables</th>
<%
Dim var
For Each var in Request.ServerVariables
    Call Response.Write("<TR>")
    Call Response.Write("<TD><B>" & var & "</B>:</TD>")
    Call Response.Write("<TD>" & Request.ServerVariables(var) _
      & "</TD>")
    Call Response.Write("</TR>")
Next
%>
</table>

Use the –prov option to identify the name of the ProtectedConfigurationProvider that will perform the encryption and decryption. If you do not specify a provider using the -prov option, the provider configured as the defaultProvider is used.

Un ejemplo que encripta el connectionstring del web.config
aspnet_regiis -pe "connectionStrings" -app "/SampleApplication" -prov "RsaProtectedConfigurationProvider"

Para desencriptar :
aspnet_regiis -pd "connectionStrings" -app "/SampleApplication"




Para MicrosoftCRM utilizo el siguiente aspx para sacar las serverVariables


<%@ Page language="vb" Inherits="Microsoft.Crm.Web.Loader" %>
<%@ Register TagPrefix="loc" Namespace="Microsoft.Crm.Application.Controls.Localization" Assembly="Microsoft.Crm.Application.Components.Application" %>
<%@ Register TagPrefix="cnt" Namespace="Microsoft.Crm.Application.Controls" Assembly="Microsoft.Crm.Application.Components.Application" %>
<%@ Import Namespace="Microsoft.Crm.Utility" %>
<%@ Import Namespace="Microsoft.Crm.Application.Pages.Common" %>
<html>
<table BORDER="1">
<th COLSPAN="2">ServerVariables</th>
<%
Dim var
For Each var in Request.ServerVariables
    Call Response.Write("<TR>")
    Call Response.Write("<TD><B>" & var & "</B>:</TD>")
    Call Response.Write("<TD>" & Request.ServerVariables(var) _
      & "</TD>")
    Call Response.Write("</TR>")
Next
%>
</table>
</body>

</html>

CRM 4.0 - Acceso y autenticación desde asp a crm con acceso a registro

using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Win32;
namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        public string orgname;
        public string crmurl;
        public string metaurl;
        public bool offline;
        protected void Page_Load(object sender, EventArgs e)
        {
            #region CRM URLs and Organization Name
            //Determine Offline State from Host Name
            Response.Write(Request.Url.Host.ToString());
            if (Request.Url.Host.ToString() == "127.0.0.1")
            {
                offline = true;
                //Retrieve the Port and OrgName from the Registry
                RegistryKey regkey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\MSCRMClient");
                orgname = regkey.GetValue("ClientAuthOrganizationName").ToString();
                string portnumber = regkey.GetValue("CassiniPort").ToString();
                //Construct the URLs
                string baseurl = "http://localhost:" + portnumber + "/mscrmservices/2007/";
                crmurl = baseurl + "crmservice.asmx";
                metaurl = baseurl + "metadataservice.asmx";
            }
            else
            {
                offline = false;
                //Retrieve the URLs from the Registry
                RegistryKey regkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");
                string ServerUrl = regkey.GetValue("ServerUrl").ToString();
                crmurl = ServerUrl + "/2007/crmservice.asmx";
                metaurl = ServerUrl + "/2007/metadataservice.asmx";
                //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;
                    }
                }
                if (string.IsNullOrEmpty(orgname))
                {
                    //Windows Auth URL
                    if (Request.Url.Segments[2].TrimEnd('/').ToLower() == "isv")
                    {
                        orgname = Request.Url.Segments[1].TrimEnd('/').ToLower();
                    }
                    //IFD URL
                    if (string.IsNullOrEmpty(orgname))
                    {
                        string url = Request.Url.ToString().ToLower();
                        int start = url.IndexOf("://") + 3;
                        orgname = url.Substring(start, url.IndexOf(".") - start);
                    }
                }
            }
            #endregion

            using (new CrmImpersonator())
            {
                CrmAuthenticationToken token;
                if (offline == true)
                {
                    token = new CrmAuthenticationToken();
                }
                else
                {
                    // Notice that the Context parameter value is Page.Context.
                    token = CrmAuthenticationToken.ExtractCrmAuthenticationToken(Context, orgname);
                }
                token.OrganizationName = orgname;
                token.AuthenticationType = 0;
                //Create the Service
                CrmService service = new CrmService();
                service.Credentials = System.Net.CredentialCache.DefaultCredentials;
                service.CrmAuthenticationTokenValue = token;
                service.Url = crmurl;
            // This code shows how to create the metadata service.
            // It is not used in this sample.

            // MetadataService meta = new MetadataService();
            // meta.CrmAuthenticationTokenValue = token;
            // meta.Credentials = CredentialCache.DefaultCredentials;
            // meta.Url = "http://localhost/mscrmservices/2007/MetadataService.asmx";

                account account = new account();
                account.name = "Offline Impersonator: " + DateTime.Now.TimeOfDay.ToString();
                if (offline == false)
                    // Explicitly set the owner ID for the record if not offline.
                    account.ownerid = new Owner("systemuser", token.CallerId);
                service.Create(account);
            }
            Response.Write("Done");
        }
    }
}

CRM 4.0 - Acceder al crm desde fuera sin usar webservice


Inclusión de la función de conexión


private CrmService GetCrmService(string organizationName) {
            // Setup the Authentication Token
            CrmAuthenticationToken token = new CrmAuthenticationToken();
            token.OrganizationName = organizationName;
            CrmService crmService = new CrmService();
            crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
            crmService.CrmAuthenticationTokenValue = token;
            return crmService;
        }



En el programa principal se conecta


     #region Proceso de conexión

            crmService = GetCrmService("organizacion");
            crmService.Credentials = new System.Net.NetworkCredential("usuario", "pass", "domain");
            crmService.Url = "http://127.0.0.1/MSCrmServices/2007/CrmService.asmx";

            #endregion

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);
        }

...

CRM 4.0 - Acceso a CRM desde .NET


private CrmService.CrmService GetCrmService(string organizationName) {
        // Setup the Authentication Token
        CrmService.CrmAuthenticationToken token = new CrmAuthenticationToken();
        token.OrganizationName = organizationName;
        CrmService.CrmService crmService = new CrmService.CrmService();
        crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
        crmService.CrmAuthenticationTokenValue = token;
        return crmService;
}

CrmService.CrmService crmService = GetCrmService(organizationName);
crmService.Credentials = new System.Net.NetworkCredential("usuario", "password", "dominio.com");


--------------------------------------------------------------------------------------------------------------------


/// <summary>
/// Retrieves all the CRM Organizations available on the server
/// </summary>
private void GetOrganizations() {

        //Authenticate with the DiscoveryService using
        //Active Directory Windows Integrated Security
        CrmDiscoveryService.CrmDiscoveryService discoveryService = new CrmDiscoveryService.CrmDiscoveryService();
        //discoveryService.Credentials = System.Net.CredentialCache.DefaultCredentials;
        discoveryService.Credentials = new System.Net.NetworkCredential("usuario","password","dominio.com");
        //Make request for organization information
        RetrieveOrganizationsRequest orgsRequest = new RetrieveOrganizationsRequest();
        RetrieveOrganizationsResponse orgsResponse = (RetrieveOrganizationsResponse)discoveryService.Execute(orgsRequest);

        //Populate the organizations
        for (int i = 0; i < orgsResponse.OrganizationDetails.Length; i++) {
            ddlOrganizations.Items.Add(new ListItem(orgsResponse.OrganizationDetails[i].OrganizationName, orgsResponse.OrganizationDetails[i].OrganizationId.ToString()));
        }
}

viernes, 13 de septiembre de 2013

CRM 4.0 - Todo sobre entidades dynamicas en crm

Actualizar a nulo un campo de datetime

CrmDateTime NullTime = new CrmDateTime();
NullTime.IsNull = true;
NullTime.IsNullSpecified = true;
           
proyectoDinamico.Properties.Add(new CrmDateTimeProperty("new_fechaestimadacierredinamica", NullTime));


Recuperar un string de el contexto de un plugin (Entidad dinámica)

Microsoft.Crm.Sdk.DynamicEntity target = (Microsoft.Crm.Sdk.DynamicEntity)context.InputParameters.Properties["Target"];
string domainname= target.Properties["domainname"].ToString();

Recuperar otro tipo de dato de una entidad dinámica

CrmNumber workItemHours = entity.Properties["new_budgetedhours"] as CrmNumber;
o otro modo:
Guid projectid = ((CrmSdk.Lookup)entity.Properties["new_projectid"]).Value;

Comprobar una propiedad del tipo string en un if

if (((string)postOportunidad.Properties["statecode"]) == "Open") {
...
}


Modifica el valor del atributo de una entidad dinámica

tarea.Properties["new_horastotales"] = new CrmDecimal(horasTarea);


Crear, borrar y modificar entidades dinámicas

  * Crear
  // Create the target.
                TargetCreateDynamic targetCreateSinonimoNuno = new TargetCreateDynamic();
                targetCreateSinonimoNuno.Entity = sinonimoNuno;
                // Create the request object.
                CreateRequest createSinonimoNuno = new CreateRequest();
                // Set the properties of the request object.
                createSinonimoNuno.Target = targetCreateSinonimoNuno;
                // Execute the request.
                CreateResponse created = (CreateResponse)crmService.Execute(createSinonimoNuno);

  * Recuperar
  // Retrieve the target.
                TargetRetrieveDynamic targetRetrieve = new TargetRetrieveDynamic();
                targetRetrieve.EntityId = PrePrograma.Value;
                targetRetrieve.EntityName = EntityName.product.ToString();
                // Retrieve the request object.
                RetrieveRequest retrieve = new RetrieveRequest();
                // Set the properties of the request object.
                retrieve.Target = targetRetrieve;
  retrieve.ReturnDynamicEntities = true;
  columnasProspect.Attributes.Add("new_lineadenegocioid");
                retrieve.ColumnSet = columnasProspect;
                // Execute the request.
                RetrieveResponse retrieved = (RetrieveResponse)crmService.Execute(retrieve);

  * Recuperar multiples
  sinonimoGuid = ((Key)sinonimo.Properties["new_sinonimoid"]).Value;
  //Recupero la unidad estandar del CRM
                        QueryByAttribute querySinonimoNuno = new QueryByAttribute();
                        colsNunoNif.Attributes.Add("new_sinonimoid");
                        colsNunoNif.Attributes.Add("new_nunoid");
                        querySinonimoNuno.ColumnSet = colsNunoNif;
                        querySinonimoNuno.EntityName = "new_sinonimonuno";
                        querySinonimoNuno.Attributes = new string[] { "new_sinonimoid" };
                        querySinonimoNuno.Values = new object[] { sinonimoGuid };
                        RetrieveMultipleRequest requestSinonimoNuno = new RetrieveMultipleRequest();
                        requestSinonimoNuno.ReturnDynamicEntities = true;
                        requestSinonimoNuno.Query = querySinonimoNuno;
                        RetrieveMultipleResponse retrievedSinonimoNuno = (RetrieveMultipleResponse)crmService.Execute(requestSinonimoNuno);
                        if (retrievedSinonimoNuno.BusinessEntityCollection.BusinessEntities.Count > 0) {

  * Actualizar

  // Create the update target.
             TargetUpdateDynamic updateDynamic = new TargetUpdateDynamic();
             // Set the properties of the target.
             updateDynamic.Entity = entity;
             //   Create the update request object.
             UpdateRequest update = new UpdateRequest();
             //   Set request properties.
             update.Target = updateDynamic;
             //   Execute the request.
             UpdateResponse updated = (UpdateResponse)crmService.Execute(update);


  * Eliminar

    TargetDeleteDynamic targetDeleteControlCostes = new TargetDeleteDynamic();
                  targetDeleteControlCostes.EntityName = "new_controldecoste";
                  targetDeleteControlCostes.EntityId = controlCostesGuid;
                  DeleteRequest deleteControlCostesReq = new DeleteRequest();
                 
                  deleteControlCostesReq.Target = targetDeleteControlCostes;
                  DeleteResponse deleteControlCostesResp = (DeleteResponse)crmService.Execute(deleteControlCostesReq);

Igualmente con Update, Delete, etc.


Añadir un atributo a una entidad dinámica

Siendo Cliente una entidad dinamica

      Key KeyContact = new Key();
                    KeyContact.Value = new Guid(context.OutputParameters.Properties["id"].ToString());
                   
                    Cliente.Properties.Add(new KeyProperty("accountid", KeyContact));

      //Si usas el Web Service el metodo Add no existe y has de usarlo de este modo
             //Creas por un lado las propiedades
      CrmBooleanProperty P_bool = new CrmBooleanProperty();
                    P_bool.Value = new CrmBoolean();
                    P_bool.Name = "new_Reconfirmacion";
                    P_bool.Value.Value = true;
                    KeyProperty P_key = new KeyProperty();
                    P_key.Name = "activityid";
                    P_key.Value = Respuestas.activityid;

//Y las añades a la entidad dinamica asi:
respuestaDinamica.Properties = new Property[] {P_bool, P_key};

             //Otra manera de añadir atributos
      //Creacion del producto de la oportunidad
                productoOportunidad.Properties.Add(new LookupProperty("opportunityid",new Lookup("opportunity",OportunityId)));
                productoOportunidad.Properties.Add(new LookupProperty("productid",new Lookup("product",ProductoId)));
                productoOportunidad.Properties.Add(new LookupProperty("uomid",new Lookup("uom",UnidadMedidaId)));
                productoOportunidad.Properties.Add(new CrmMoneyProperty("priceperunit", precioUnidad));
                productoOportunidad.Properties.Add(new CrmDecimalProperty("quantity",precioTotal));
                productoOportunidad.Properties.Add(new CrmMoneyProperty("baseamount", importe));
                productoOportunidad.Properties.Add(new CrmBooleanProperty("new_lineaprincipal", new CrmBoolean(true)));



Preguntar si una entidad dinamica tiene un determinado atributo

Siendo Cliente una entidad dinamica

     
if ( Cliente.Properties.Contains("originatingleadid") ) {
...
}


//Esta funcion se utiliza para convertir una entidad dinamica en una bussines entity que podremos
//utilizar para actualizar o crear entidades con el webservice


incluir -> using System.Reflection;
/// <summary>
        /// Convert a dynamic entity into a strongly typed business entity.
        /// </summary>
        public static BusinessEntity Convert(DynamicEntity entity) {
            string coreEntityName = entity.Name;
     //ATENCION !!!!!! cambiar new email() por la entidad que corresponda !!!!!
            Type entType = (new email()).GetType();
            ConstructorInfo init = entType.GetConstructor(new Type[] { });
            object ent = init.Invoke(new object[] { });
            foreach (Property p in entity.Properties) {
                PropertyInfo entProp = entType.GetProperty(p.Name);
                if (null == entProp) {
                    Console.WriteLine("Could not find attribute {0} on entity {1}.", p.Name, coreEntityName);
                }
                else {
                   
                        entProp.SetValue(ent, GetAttribute(entity, p.Name), null);
                   
                }
            }
            return (BusinessEntity)ent;
        }

....

Un ejemplo de su uso seria:


  DynamicEntity Cliente = new DynamicEntity();

  //***Aqui se hace algo con la entidad dinamica***

  Cliente = (DynamicEntity)context.InputParameters.Properties["Target"];

  //***********************************************

  BusinessEntity ClienteFisico = Convert(Cliente);
                account Account = (account)ClienteFisico;
                Account.accountid = new Key();
               
                if (context.OutputParameters.Properties.Contains("id"))
                    Account.accountid.Value = new Guid(context.OutputParameters.Properties["id"].ToString());

  //Finalmente se actualiza
                service.Update(Account);



Crea, Actualiza o Borra una entidad dinamica con el servicio web


      TargetUpdateDynamic Aval = new TargetUpdateDynamic();
                    Aval.Entity = entity;
                    UpdateRequest update = new UpdateRequest();
                    update.Target = Aval;


---------------------------------------------------------------------------------------------
incluir -> using System.Reflection;
 /// <summary>
        /// This method returns the value of a dynamic entity attribute.
        /// </summary>
        public static object GetAttribute(BusinessEntity entity, string attribute) {
            if (entity.GetType() == typeof(DynamicEntity)) {
                DynamicEntity de = (DynamicEntity)entity;
                foreach (Property prop in de.Properties) {
                    if (prop.Name == attribute) {
                        PropertyInfo propInfo = prop.GetType().GetProperty("Value");
                        return propInfo.GetValue(prop, null);
                    }
                }
                return null;
            }
            else {
                PropertyInfo propInfo = entity.GetType().GetProperty(attribute);
                return propInfo.GetValue(entity, null);
            }
        }
---------------------------------------------------------------------------------------------

DynamicEntity emaildinamico = new DynamicEntity();
emaildinamico.Name = EntityName.email.ToString();
...

//((DynamicEntity)context.InputParameters.Properties["Target"]).Properties["
subject"] = "hola";
//emaildinamico = (DynamicEntity)context.InputParameters.Properties["Target"];
//PropertyBagCollection target = context.InputParameters.Properties["Target"];
//target.



Hacer un retrieve en una entidad dinámica


  // Create the request.
                RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
                retrieve.ReturnDynamicEntities = true;
                retrieve.Query = qe.Query;
                // Execute the request.
                RetrieveMultipleResponse retrieved2 = (RetrieveMultipleResponse)crmService.Execute(retrieve);
                DynamicEntity entidad_recuperada = new DynamicEntity();
                entidad_recuperada.Name = entity;
                object valor_atributo;
                if (retrieved2.BusinessEntityCollection.BusinessEntities.Length > 0) {
                    for (int i = 0; i < retrieved2.BusinessEntityCollection.BusinessEntities.Length;i++ ) {
                        BusinessEntity be = retrieved2.BusinessEntityCollection.BusinessEntities[i];
                        entidad_recuperada = (DynamicEntity)be;
                        valor_atributo = GetAttribute(entidad_recuperada, atributo);



GetAttribute: Funcion para recuperar el campo de una entidad dinámica

 /// <summary>
        /// This method returns the value of a dynamic entity attribute.
        /// </summary>
        public static object GetAttribute(BusinessEntity entity, string attribute) {
            if (entity.GetType() == typeof(DynamicEntity)) {
                DynamicEntity de = (DynamicEntity)entity;
                foreach (Property prop in de.Properties) {
                    if (prop.Name == attribute) {
                        PropertyInfo propInfo = prop.GetType().GetProperty("Value");
                        return propInfo.GetValue(prop, null);
                    }
                }
                return null;
            }
            else {
                PropertyInfo propInfo = entity.GetType().GetProperty(attribute);
                return propInfo.GetValue(entity.ToString(), null);
            }
        }



Trabajo con entidades Dinamicas SDK



[C#]
using System;
using System.Collections;
using CrmSdk;
using Microsoft.Crm.Sdk.Utility;
namespace Microsoft.Crm.Sdk.HowTo
{
   /// <summary>
   /// This sample shows how to create a contact with a DynamicEntity and
   ///  retrieve it as a DynamicEntity.
   /// </summary>
   public class DynamicEntityHowTo
   {
      static void Main(string[] args)
      {
         // TODO: Change the server URL and organization to match your Microsoft
         // Dynamics CRM Server and Microsoft Dynamics CRM organization.
         DynamicEntityHowTo.Run("http://localhost:5555", "CRM_SDK");
      }
      public static bool Run(string crmServerUrl, string orgName)
      {
         bool success = false;
         try
         {
            // Set up the CRM Service.
         CrmService service = CrmServiceUtility.GetCrmService(crmServerUrl, orgName);


            #region Setup Data Required for this Sample
            // Create the account object.
            account account = new account();
            account.name = "Fourth Coffee";
            // Create the target object for the request.
            TargetCreateAccount target = new TargetCreateAccount();
            target.Account = account;
            // Create the request object.
            CreateRequest createRequest = new CreateRequest();
            createRequest.Target = target;
        
            // Execute the request.
            CreateResponse createResponse = (CreateResponse)service.Execute(createRequest);
            Guid accountID = createResponse.id;
            #endregion


Create Contact Dynamically



            #region Create Contact Dynamically
            // Set the properties of the contact using property objects.
            StringProperty firstname = new StringProperty();
            firstname.Name = "firstname";
            firstname.Value = "Jesper";
            StringProperty lastname = new StringProperty();
            lastname.Name = "lastname";
            lastname.Value = "Aaberg";
        
            // Create the DynamicEntity object.
            DynamicEntity contactEntity = new DynamicEntity();
            // Set the name of the entity type.
            contactEntity.Name = EntityName.contact.ToString();
            // Set the properties of the contact.
            contactEntity.Properties = new Property[] {firstname, lastname};
     
            // Create the target.
            TargetCreateDynamic targetCreate = new TargetCreateDynamic();
            targetCreate.Entity = contactEntity;
            // Create the request object.
            CreateRequest create = new CreateRequest();
            // Set the properties of the request object.
            create.Target = targetCreate;
            // Execute the request.
            CreateResponse created = (CreateResponse) service.Execute(create);
        
            #endregion


Retrieve Contact Dynamically


        
            #region Retrieve Contact Dynamically
            // Create the retrieve target.
            TargetRetrieveDynamic targetRetrieve = new TargetRetrieveDynamic();
            // Set the properties of the target.
            targetRetrieve.EntityName = EntityName.contact.ToString();
            targetRetrieve.EntityId = created.id;
            // Create the request object.
            RetrieveRequest retrieve = new RetrieveRequest();
            // Set the properties of the request object.
            retrieve.Target = targetRetrieve;
            retrieve.ColumnSet = new AllColumns();
            // Indicate that the BusinessEntity should be retrieved as a DynamicEntity.
            retrieve.ReturnDynamicEntities = true;
            // Execute the request.
            RetrieveResponse retrieved = (RetrieveResponse) service.Execute(retrieve);
            // Extract the DynamicEntity from the request.
            DynamicEntity entity = (DynamicEntity)retrieved.BusinessEntity;
            // Extract the fullname from the dynamic entity
            string fullname;
            for (int i = 0; i < entity.Properties.Length; i++)
            {
               if (entity.Properties[i].Name.ToLower() == "fullname")
               {
                  StringProperty property = (StringProperty) entity.Properties[i];
                  fullname = property.Value;
                  break;
               }
            }
            #endregion


Update the DynamicEntity



            #region  Update the DynamicEntity
            // This part of the example demonstrates how to update properties of a
            // DynamicEntity. 
            // Set the contact properties dynamically.
            // Contact Credit Limit
            CrmMoneyProperty money = new CrmMoneyProperty();
            // Specify the property name of the DynamicEntity.
            money.Name="creditlimit";
            money.Value = new CrmMoney();
            // Specify a $10000 credit limit.
            money.Value.Value=10000M;
            // Contact PreferredContactMethodCode property
            PicklistProperty picklist = new PicklistProperty();
            //   Specify the property name of the DynamicEntity.
            picklist.Name="preferredcontactmethodcode";
            picklist.Value = new Picklist();
            //   Set the property's picklist index to 1.
            picklist.Value.Value = 1;
            // Contact ParentCustomerId property.
            CustomerProperty parentCustomer = new CustomerProperty();
            //   Specify the property name of the DynamicEntity.
            parentCustomer.Name = "parentcustomerid";
            parentCustomer.Value = new Customer();
            //   Set the customer type to account.
            parentCustomer.Value.type = EntityName.account.ToString();
            //   Specify the GUID of an existing CRM account.
            // SDK:parentCustomer.Value.Value = new Guid("A0F2D8FE-6468-DA11-B748-000D9DD8CDAC");
            parentCustomer.Value.Value = accountID;
            //   Update the DynamicEntities properties collection to add new properties.
            //   Convert the properties array of DynamicEntity to an ArrayList.
            ArrayList arrProps = new ArrayList(entity.Properties);
           
            //   Add properties to ArrayList.
            arrProps.Add(money);
            arrProps.Add(picklist);
            arrProps.Add(parentCustomer);
            //   Update the properties array on the DynamicEntity.
            entity.Properties = (Property[])arrProps.ToArray(typeof(Property));
            // Create the update target.
            TargetUpdateDynamic updateDynamic = new TargetUpdateDynamic();
            // Set the properties of the target.
            updateDynamic.Entity = entity;
            //   Create the update request object.
            UpdateRequest update = new UpdateRequest();
            //   Set request properties.
            update.Target = updateDynamic;
            //   Execute the request.
            UpdateResponse updated = (UpdateResponse)service.Execute(update);
           
            #endregion

            #region check success
            if (retrieved.BusinessEntity is DynamicEntity)
            {
               success =  true;
            }
            #endregion

  
            #region Remove Data Required for this Sample
            service.Delete(EntityName.contact.ToString(), created.id);
            service.Delete(EntityName.account.ToString(), accountID);
            #endregion

         }
         catch (System.Web.Services.Protocols.SoapException ex)
         {
            // Add your error handling code here...
            Console.WriteLine(ex.Message + ex.Detail.InnerXml);
         }
        
         return success;
      }
   }
}