// ** Create a memo attribute **
MemoAttributeMetadata memoAttribute = new MemoAttributeMetadata
{
// Set base properties
SchemaName = "new_memo",
DisplayName = new Label("Sample Memo", 1033),
RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
Description = new Label("Memo Attribute", 1033),
// Set extended properties
Format = StringFormat.TextArea,
ImeMode = ImeMode.Disabled,
MaxLength = 500
};
// Create the request.
CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest
{
EntityName = "EntityLogicalName",
Attribute = memoAttribute
};
// Execute the request. Get Response
CreateAttributeResponse resp = (CreateAttributeResponse)_service.Execute(createAttributeRequest);
Create a memo attribute
CanBeReferenced Entity Request
// ** CanBeReferenced Entity Request **
//Checks whether the specified entity can be the primary entity in one-to-many relationship.
// REQUEST
CanBeReferencedRequest canBeReferencedRequest = new CanBeReferencedRequest
{
EntityName = "referencedEntity(Primary Entity)" //Primary Entity Name
};
// RESPONSE
CanBeReferencedResponse canBeReferencedResponse =
(CanBeReferencedResponse)_service.Execute(canBeReferencedRequest);
// Verify RESPONSE
if (!canBeReferencedResponse.CanBeReferenced)
{
Console.WriteLine(
"Entity {0} can't be the primary entity in this one-to-many relationship",
"referencedEntity(Primary Entity)");
}
Create Entity request
// ** Create Entity request **
// Desc: Creates an entity in the current Organization
CreateEntityRequest cent = new CreateEntityRequest();
// Entity Metadata
cent.Entity = new Microsoft.Xrm.Sdk.Metadata.EntityMetadata(){
SchemaName = "_customEntity",
DisplayName = new Label("_custom",1033),
DisplayCollectionName = new Label("_customentities",1033),
Description = new Label("created using Entity request",1033),
OwnershipType = OwnershipTypes.OrganizationOwned,
IsActivity=false
};
// Attribute metadata
cent.PrimaryAttribute = new StringAttributeMetadata()
{
SchemaName = "new_accountname",
RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
MaxLength = 100,
Format = StringFormat.Text,
DisplayName = new Label("Account Name", 1033),
Description = new Label("The primary attribute for the Bank Account entity.", 1033)
};
// Executes the request(Org service)
_service.Execute(cent);
Ajax Programming
var http_request = false;
var ser = Math.round(Math.random()*1000000); // Anti-caching serial number
var debug = false; // Set to true to show the full server response
function ajax(httpRequestMethod, url, parameters, target)
{
http_request = false;
document.getElementById(target).innerHTML = 'Wait...'
if (window.XMLHttpRequest)
{ // For Mozilla, Safari, Opera, IE7
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType)
{
http_request.overrideMimeType('text/plain');
//Change MimeType to match the data type of the server response.
//Examples: "text/xml", "text/html", "text/plain"
}
}
else if (window.ActiveXObject)
{ // For IE6
try
{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{}
}
}
if (!http_request)
{
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function() {updateElement(target);};
if (httpRequestMethod == 'GET')
{
http_request.open('GET', url + '?' + parameters, true);
http_request.send(null);
ser = ser + 1;
}
else if (httpRequestMethod == 'POST')
{
http_request.open('POST', url, true);
http_request.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
http_request.send(parameters);
}
else
{
alert('Sorry, unsupported HTTP method');
}
}
function updateElement(target)
{
if (http_request.readyState == 4)
{
if (debug == true)
{
alert(http_request.responseText);
}
if (http_request.status == 200)
{
document.getElementById(target).innerHTML =
http_request.responseText;
}
else if (debug == false)
{
alert('The server returned an error. Please set debug = true to see the full server response.');
}
}
}
XMLHttpRequest
Summary of the specification by W3C, and usage
This server side object is used by JavaScript to exchange data with the server, in plain text, XML or JSON format. The XML format is automatically parsed by the object at loading and accessible by DOM's methods. JSON files are parsed by the eval() JavaScript command. In Internet Explorer, it is an Active X object.
The connection takes several successive states that are assigned to the readyState attribute of the object. When the final state is reached, the data may be found in another attribute. It may be a plain text or an XML document. The JSON format is loaded as plain text and parsed by JavaScript. More details on the use of the class in the Ajax tutorial.
0 Not initialized
1 Open
2 Sent
3 Received
4 Loaded
404 if the page is not found.
url: the location of the file, with a path. boolean: true (asynchronous) / false (synchronous). optionally, a login and a password as additional arguments.
This server side object is used by JavaScript to exchange data with the server, in plain text, XML or JSON format. The XML format is automatically parsed by the object at loading and accessible by DOM's methods. JSON files are parsed by the eval() JavaScript command. In Internet Explorer, it is an Active X object.
Brief history
XMLHttpRequest, was first implemented by Internet Explorer since the 4.0 version. The same concept was named XMLHTTP some times, before the Ajax name becomes commonly used. The use of XMLHttpRequest in 2005 by Google, in Gmail and GoogleMaps has contributed to the success of this technology.Description
This is a class that is recognized by all current browsers, and by the JavaScript client side programming language. For each request to the server, a new instance is created by a call to the constructor. The open method starts the connection, in read or write mode, to receive data from the server or send it. It will be processed by the server with a server side language as PHP, Java, etc...The connection takes several successive states that are assigned to the readyState attribute of the object. When the final state is reached, the data may be found in another attribute. It may be a plain text or an XML document. The JSON format is loaded as plain text and parsed by JavaScript. More details on the use of the class in the Ajax tutorial.
Attributes
The purpose of attributes of the class is to be assigned the status of the connection, and to hold data.unsigned short readyState
The code successively changes value until the server is ready, from 0 to 4 .0 Not initialized
1 Open
2 Sent
3 Received
4 Loaded
status(unsigned short)
200 is ok404 if the page is not found.
statusText(DOMString)
Holds the label of the status, corresponding to the status code.responseText(DOMString)
Holds loaded data as a string of characters. It is completely filled when the status is 4.responseXml(DOMDocument)
Holds an XML loaded file, and DOM's methods allow to extract data. It is filled only when the code is 4 and null otherwise.onreadystatechange(EventListener)
Invoked when readyState is assigned.Methods
Apart the constructor, the class has two main methods, open to create a session and designate the distant file, and send to move data to the server.abort()
Resets the object and stops any activity created by the object.getAllResponseHeaders()
Return all headers into a string, separated by CR and LF codes.getResponseHeader(DOMString)
Return the header of data received, after the last request. Several headers should be separated by a comma plus a space.open(mode, url, boolean [,login, password])
mode: type of request, GET, POST, HEAD or other http methods.url: the location of the file, with a path. boolean: true (asynchronous) / false (synchronous). optionally, a login and a password as additional arguments.
send("string")
null or empty with a GET command, a string otherwise. Raises a DOMException (INVALID_STATE_ERR) if the readyState code is not1. setRequestHeader(DOMString,DomString) Arguments are the name of the header and the value. Several values may be successively sent. Raises a DOMException (INVALID_STATE_ERR) if the readyState code is not 1.How to use XMLHttpRequest
The class is a part of ECMAScript (JavaScript) and used as any other class of the language, but there are several constructors according to the browser. Here is a complete code to open an Ajax session, by creating a new XMLHttpRequest object and loading some data. The code may be tested with several demos on the Ajax tutorial and in the Ajax sub-domain.function submitForm()
{
var xhr=null;
try
{
xhr = new XMLHttpRequest();
}
catch(e)
{
try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e2)
{
try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {}
}
}
xhr.onreadystatechange = function(){
document.ajax.dyn.value="Wait server...";
if(xhr.readyState == 4)
{
if(xhr.status == 200)
{
document.ajax.dyn.value="Received:" +
xhr.responseText;
}
else
{
document.ajax.dyn.value="Error: returned statuscode " + xhr.status + " " + xhr.statusText;
}
}
};
xhr.open("GET", "data.xml", true);
xhr.send(null);
}
Caching problem
Memory cache does not work properly with the object. Often, the file loaded by the GET method is not the last version, but an older version taken from the memory buffer. If the file is not too big, this can be overcomed easily by adding a parameter to the command. Replace: xhr.open("GET", "data.xml", true); by: xhr.open("GET", "data.xml?nocache=" + Math.random(),true);The HTML format
We can load XML files, can we load also HTML or XHTML files? Actually, this is planned for the next specification of the XMLHttpRequest object as it is planned to access cross-domains files. It is planned that, in this case, the text/html mime type will be used, while the text/xml type is used for XML documents, in the content type header. For now, a replacing solution exists, the pseudo responseHTML attribute, that is given on this site.Specification
W3C Working Draft specification for XMLHttpRequest. The W3C is working on a new version of the standard, called XMLHttpRequest Level 2. New improvements are cross-site requests, progress events, and the handling of byte streams for both sending and receiving. Besides the XMLHttpRequest object itself, W3C has established a specification for cross-site exchanges named Access Control. However Microsoft has choosen to not support the proptocol and offers in Internet Explorer 8 an alternative named XDomainRequest. This object could replace XMLHttpRequest or not depending its support for all features of XHR in the final version.CRM 4.0 PLuGIN: sample plugin with pre & post Images
p u b l i c v o i d E x e c u t e ( I P l u g i n E x e c u t i o n C o n t e x t c o n t e x t )
{
s t r i n g m _ O p p o r t u n i t y N ame = s t r i n g . E mp t y ;
s t r i n g m _ O p p o r t u n i t y I d = s t r i n g . E mp t y ;
i f ( c o n t e x t . M e s s a g e N ame . E q u a l s ( " C r e a t e " ) )
{
/ / E n t i t y c r e a t i o n . D y n am i c E n t i t y p o s t E n t i t y ;
i f ( c o n t e x t . P o s t E n t i t y I ma g e s . C o n t a i n s ( " T a r g e t " ) )
{
p o s t E n t i t y = ( ( D y n am i c E n t i t y ) c o n t e x t . P o s t E n t i t y I ma g e s [ " T a r g e t " ] ) ;
i f ( p o s t E n t i t y . P r o p e r t i e s . C o n t a i n s ( " o p p o r t u n i t y i d " ) )
{
K e y o p p o r t u n i t y I d = ( K e y ) p o s t E n t i t y . P r o p e r t i e s [ " o p p o r t u n i t y i d " ] ;
i f ( o p p o r t u n i t y I d ! = n u l l ) { m _ O p p o r t u n i t y I d = o p p o r t u n i t y I d . V a l u e . T o S t r i n g ( ) ;
}
}
i f ( p o s t E n t i t y . P r o p e r t i e s . C o n t a i n s ( " n ame " ) )
{
m _ O p p o r t u n i t y N ame = p o s t E n t i t y . P r o p e r t i e s [ " n ame " ] . T o S t r i n g ( ) ;
}
}
}
e l s e i f ( c o n t e x t . M e s s a g e N ame . E q u a l s ( " U p d a t e " ) )
{
/ / E n t i t y u p d a t e . D y n am i c E n t i t y p r e t E n t i t y ;
D y n am i c E n t i t y p o s t E n t i t y ;
i f ( c o n t e x t . P r e E n t i t y I ma g e s . C o n t a i n s ( " T a r g e t " ) )
{
p r e t E n t i t y = ( ( D y n am i c E n t i t y ) c o n t e x t . P r e E n t i t y I ma g e s [ " T a r g e t " ] ) ;
}
i f ( c o n t e x t . P o s t E n t i t y I ma g e s . C o n t a i n s ( " T a r g e t " ) )
{
p o s t E n t i t y = ( ( D y n am i c E n t i t y ) c o n t e x t . P o s t E n t i t y I ma g e s [ " T a r g e t " ] ) ;
}
i f ( p o s t E n t i t y . P r o p e r t i e s . C o n t a i n s ( " o p p o r t u n i t y i d " ) )
{ K e y o p p o r t u n i t y I d = ( K e y ) p o s t E n t i t y . P r o p e r t i e s [ " o p p o r t u n i t y i d " ] ;
i f ( o p p o r t u n i t y I d ! = n u l l ) { m _ O p p o r t u n i t y I d = o p p o r t u n i t y I d . V a l u e . T o S t r i n g ( ) ;
}
}
i f ( p o s t E n t i t y . P r o p e r t i e s . C o n t a i n s ( " n ame " ) )
{
m _ O p p o r t u n i t y N ame = p o s t E n t i t y . P r o p e r t i e s [ " n ame " ] . T o S t r i n g ( ) ;
}
}
}
{
s t r i n g m _ O p p o r t u n i t y N ame = s t r i n g . E mp t y ;
s t r i n g m _ O p p o r t u n i t y I d = s t r i n g . E mp t y ;
i f ( c o n t e x t . M e s s a g e N ame . E q u a l s ( " C r e a t e " ) )
{
/ / E n t i t y c r e a t i o n . D y n am i c E n t i t y p o s t E n t i t y ;
i f ( c o n t e x t . P o s t E n t i t y I ma g e s . C o n t a i n s ( " T a r g e t " ) )
{
p o s t E n t i t y = ( ( D y n am i c E n t i t y ) c o n t e x t . P o s t E n t i t y I ma g e s [ " T a r g e t " ] ) ;
i f ( p o s t E n t i t y . P r o p e r t i e s . C o n t a i n s ( " o p p o r t u n i t y i d " ) )
{
K e y o p p o r t u n i t y I d = ( K e y ) p o s t E n t i t y . P r o p e r t i e s [ " o p p o r t u n i t y i d " ] ;
i f ( o p p o r t u n i t y I d ! = n u l l ) { m _ O p p o r t u n i t y I d = o p p o r t u n i t y I d . V a l u e . T o S t r i n g ( ) ;
}
}
i f ( p o s t E n t i t y . P r o p e r t i e s . C o n t a i n s ( " n ame " ) )
{
m _ O p p o r t u n i t y N ame = p o s t E n t i t y . P r o p e r t i e s [ " n ame " ] . T o S t r i n g ( ) ;
}
}
}
e l s e i f ( c o n t e x t . M e s s a g e N ame . E q u a l s ( " U p d a t e " ) )
{
/ / E n t i t y u p d a t e . D y n am i c E n t i t y p r e t E n t i t y ;
D y n am i c E n t i t y p o s t E n t i t y ;
i f ( c o n t e x t . P r e E n t i t y I ma g e s . C o n t a i n s ( " T a r g e t " ) )
{
p r e t E n t i t y = ( ( D y n am i c E n t i t y ) c o n t e x t . P r e E n t i t y I ma g e s [ " T a r g e t " ] ) ;
}
i f ( c o n t e x t . P o s t E n t i t y I ma g e s . C o n t a i n s ( " T a r g e t " ) )
{
p o s t E n t i t y = ( ( D y n am i c E n t i t y ) c o n t e x t . P o s t E n t i t y I ma g e s [ " T a r g e t " ] ) ;
}
i f ( p o s t E n t i t y . P r o p e r t i e s . C o n t a i n s ( " o p p o r t u n i t y i d " ) )
{ K e y o p p o r t u n i t y I d = ( K e y ) p o s t E n t i t y . P r o p e r t i e s [ " o p p o r t u n i t y i d " ] ;
i f ( o p p o r t u n i t y I d ! = n u l l ) { m _ O p p o r t u n i t y I d = o p p o r t u n i t y I d . V a l u e . T o S t r i n g ( ) ;
}
}
i f ( p o s t E n t i t y . P r o p e r t i e s . C o n t a i n s ( " n ame " ) )
{
m _ O p p o r t u n i t y N ame = p o s t E n t i t y . P r o p e r t i e s [ " n ame " ] . T o S t r i n g ( ) ;
}
}
}
Add Button in CRM Form
/* Jscript: Add button in CRM */
function ConvertToButton(fieldname, buttontext, buttonwidth,clickevent, title)
{
//check if object exists; else return
if (document.getElementById(fieldname) == null)
{
return;
}
functiontocall=clickevent;
crmForm.all[fieldname].DataValue = buttontext;
crmForm.all[fieldname].readOnly = true;
crmForm.all[fieldname].style.borderRight="#3366cc 1px solid";
crmForm.all[fieldname].style.paddingRight="5px";
crmForm.all[fieldname].style.borderTop="#3366cc 1px solid";
crmForm.all[fieldname].style.paddingLeft="5px";
crmForm.all[fieldname].style.fontSize="11px";
crmForm.all[fieldname].style.backgroundImage="url(/_imgs/btn_rest.gif)";
crmForm.all[fieldname].style.borderLeft="#3366cc 1px solid";
crmForm.all[fieldname].style.width=buttonwidth;
crmForm.all[fieldname].style.cursor="hand";
crmForm.all[fieldname].style.lineHeight="18px";
crmForm.all[fieldname].style.borderBottom="#3366cc 1px solid";
crmForm.all[fieldname].style.backgroundRepeat="repeat-x";
crmForm.all[fieldname].style.fontFamily="Tahoma";
crmForm.all[fieldname].style.height="20px";
crmForm.all[fieldname].style.backgroundColor="#cee7ff";
crmForm.all[fieldname].style.textAlign="center";
crmForm.all[fieldname].style.overflow="hidden";
crmForm.all[fieldname].attachEvent("onmousedown",push_button);
crmForm.all[fieldname].attachEvent("onmouseup",release_button);
crmForm.all[fieldname].attachEvent("onclick",functiontocall);
crmForm.all[fieldname].style.lineHeight="14px";
crmForm.all[fieldname+'_c'].style.visibility = 'hidden';
crmForm.all[fieldname].title=title;
window.focus();
function push_button(){
window.event.srcElement.style.borderWidth="2px";
window.event.srcElement.style.borderStyle="groove ridge ridge groove";
window.event.srcElement.style.borderColor="#3366cc #4080f0 #4080f0 #3366cc";
}
function release_button(){
window.event.srcElement.style.border="1px solid #3366cc";
}
}
// now the definition of the function to call on button click
function FunctionName()
{
// do something
}
Deserialize XML into an Instance of BusinessEntity
You may have a scenario where an XML representation of a BusinessEntity class needs to be parsed into an in-memory object. One example is parsing the XML representation of DynamicEntity into an instance of this class within a plug-in assembly.
This sample is a stand-alone application that demonstrates how this can be done. Included here are two sample XML files that can be successfully parsed by this application. The sample parses any BusinessEntity XML string, and if the entity is of the type DynamicEntity, its properties are printed to the console. Child entities such as calendar rules on a calendar are handled as well.
namespace CrmClient
{
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using DynamicEntity.CrmServer;
class App
{
public static void Main(string[] args)
{
App theApp = new App(args);
theApp.Run();
}
public App(string[] args)
{
_args = args;
}
private void Run()
{
if (_args.Length < 1)
{
Console.WriteLine("Usage: DynamicEntityTest");
return;
}
string fileName = _args[0];
Console.WriteLine("Reading XML from file {0}", fileName);
// Use stream reader to display XML to be parsed.
StreamReader sr = new StreamReader(fileName);
string entityXml = sr.ReadToEnd();
Console.WriteLine("XML to be parsed:");
Console.WriteLine(new string('-', 60));
Console.WriteLine("{0}", entityXml);
Console.WriteLine(new string('-', 60));
// Re-open the stream so that position is at the beginning of XML.
sr = new StreamReader(fileName);
// De-serialize the XML stream using the .NET XmlSerializer class.
XmlRootAttribute root = new XmlRootAttribute("BusinessEntity");
root.Namespace
= "http://schemas.microsoft.com/crm/2006/WebServices";
XmlSerializer xmlSerializer
= new XmlSerializer(typeof(BusinessEntity), root);
BusinessEntity entity
= (BusinessEntity)xmlSerializer.Deserialize(sr);
// End of deserialization.
Console.WriteLine("Deserialized XML into object of type {0}",
entity.GetType().FullName);
DynamicEntity dynamicEntity = entity as DynamicEntity;
if (dynamicEntity != null)
{
DisplayDynamicEntity(dynamicEntity,
"de-serialized from XML string");
}
}
///
/// Displays DynamicEntity instance and its properties.
///
private void DisplayDynamicEntity(DynamicEntity entity,
string message)
{
const string LineFormat = " {0,-30}{1,-30}{2}";
Console.WriteLine("DynamicEntity {0}: {1} with {2} properties:",
message, entity.Name, entity.Properties.Length);
Console.WriteLine(LineFormat, "Property Name", "Property Type",
"Property Value");
Console.WriteLine(LineFormat, "---", "---", "---");
foreach (Property prop in entity.Properties)
{
Type propertyType = prop.GetType();
// Format property value based on property type.
string propertyValue = string.Empty;
if (propertyType == typeof(StringProperty))
{
propertyValue = string.Format("'{0}'",
((StringProperty)prop).Value);
}
else if (propertyType == typeof(CrmDateTimeProperty))
{
CrmDateTime dt = ((CrmDateTimeProperty)prop).Value;
propertyValue
= string.Format("'{0}' date='{1}' time='{2}'",
dt.Value, dt.date, dt.time);
}
else if (propertyType == typeof(KeyProperty))
{
Key key = ((KeyProperty)prop).Value;
propertyValue = string.Format("'{0:D}'", key.Value);
}
else if (propertyType == typeof(LookupProperty))
{
Lookup lookup = ((LookupProperty)prop).Value;
propertyValue
= string.Format("'{0:D}' name='{1}' dsc='{2}'",
lookup.Value, lookup.name, lookup.dsc);
}
else if (propertyType == typeof(StateProperty))
{
string state = ((StateProperty)prop).Value;
propertyValue = string.Format("'{0}'", state);
}
else if (propertyType == typeof(DynamicEntityArrayProperty))
{
DynamicEntity[] children
= ((DynamicEntityArrayProperty)prop).Value;
propertyValue
= string.Format("number of child entities: {0}",
children.Length);
Console.WriteLine(LineFormat, prop.Name, propertyType.Name,
propertyValue);
Console.WriteLine(new string('>', 30));
int nc = 1;
foreach (DynamicEntity child in children)
{
DisplayDynamicEntity(child,
message + " - child #" + nc.ToString());
nc++;
}
Console.WriteLine(new string('<', 30));
continue;
}
else if (propertyType == typeof(OwnerProperty))
{
Owner owner = ((OwnerProperty)prop).Value;
propertyValue
= string.Format("'{0}' name='{1}' type='{2}'",
owner.Value, owner.name, owner.type);
}
else if (propertyType == typeof(CrmBooleanProperty))
{
CrmBoolean boolean = ((CrmBooleanProperty)prop).Value;
propertyValue = string.Format("'{0}'", boolean.Value);
}
else if (propertyType == typeof(PicklistProperty))
{
Picklist picklist = ((PicklistProperty)prop).Value;
propertyValue
= string.Format("'{0}', name='{1}'", picklist.Value,
picklist.name);
}
Console.WriteLine(LineFormat, prop.Name, propertyType.Name,
propertyValue);
}
}
string[] _args;
}
}
CRM 2011 CS: Assigning Lookup value
C# assign the contact to an account.
//C# assign the contact to an account.
Entity account = new Entity("account");
account["name"] = "Test Account1";
EntityReference primaryContactId = new EntityReference("contact", contactId);
account["primarycontactid"] = primaryContactId;
CRM 2011 CS: get String from a Lookup Field in crm 2011
//C# get String from a Lookup Field in crm 2011 ((EntityReference)item.Attributes["new_lookup"]).Name //C# get ID from a Lookup Field in crm 2011 ((EntityReference)item.Attributes["new_lookup"]).Id
Subscribe to:
Posts (Atom)