Saturday, 24 May 2014

public static int GetUserTimeZoneCode(ITracingService tracing, IOrganizationService service, IPluginExecutionContext context)
{
tracing.Trace("In GetUserTimeZoneCode method");
            int timeZoneCode = 0;

            try
            {
                string fetchXmls = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
                <entity name='usersettings'>
                    <attribute name='timezonecode' />
                    <link-entity name='systemuser' from='systemuserid' to='systemuserid' alias='ad'>
                        <filter type='and'>
                            <condition attribute='systemuserid' operator='eq' uitype='systemuser' value='{0}' />
                        </filter>
                    </link-entity>
                </entity>
            </fetch>";

                EntityCollection userSettings = service.RetrieveMultiple(new FetchExpression(string.Format(fetchXmls, context.UserId)));

               

Saturday, 17 May 2014

CustomWorkflowsDemos

 public class GetDateTimeNow : CodeActivity
    {
        public static DependencyProperty DateTimeNowProperty = DependencyProperty.Register("DateTimeNow", typeof(DateTime), typeof(GetDateTimeNow));

        [Output("Date and Time Now")]
        public OutArgument<DateTime> DateTimeNow
        {
            get;
            set;
        }

        protected override void Execute(CodeActivityContext context)
        {
            DateTimeNow.Set(context, DateTime.Now);
        }
    }

pluginActivities

protected override void Execute(CodeActivityContext executionContext)
        {
            try
            {
                if (executionContext == null)
                {
                    throw new InvalidPluginExecutionException("Context is Null");
                }

                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
                IWorkflowContext workflowContext = executionContext.GetExtension<IWorkflowContext>();
                IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.UserId);

                RetrieveRequest getEmail = new RetrieveRequest();
                getEmail.ColumnSet = new ColumnSet(new string[] { "siml_campaigncommunicationguid" });
                getEmail.Target = new EntityReference("email", workflowContext.PrimaryEntityId);

                RetrieveResponse currEmailResp = (RetrieveResponse)service.Execute(getEmail);

                Entity currEmail = (Entity)currEmailResp.Entity;

                Guid campaignCommunicationId = new Guid(currEmail.Attributes["siml_campaigncommunicationguid"].ToString());
                ////Guid campaignCommunicationId = new Guid("1B8B3934-B4E9-DF11-9307-001E4F330EB3");

                RetrieveRequest req = new RetrieveRequest();
                req.Target = new EntityReference("campaignactivity", campaignCommunicationId);
                req.ColumnSet = new ColumnSet(new string[] { "i5_channel", "subject", "regardingobjectid", "ownerid" });

                RetrieveResponse resp = (RetrieveResponse)service.Execute(req);

                Entity campComm = (Entity)resp.Entity;

                int campaignCommunicationChannel = ((OptionSetValue)campComm.Attributes["i5_channel"]).Value;

                string entityToUse = String.Empty;

                switch (campaignCommunicationChannel)
                {
                    case 1:
                        entityToUse = "letter";
                        break;

                    case 2:
                        entityToUse = "email";
                        break;

                    default:
                        break;
                }

                CampaignCommunicationValidator.Validator camCommValidator = new CampaignCommunicationValidator.Validator(service, campaignCommunicationId);
                List<Entity> contactsInCommunication = camCommValidator.GetValidContacts();

                foreach (Entity recipient in contactsInCommunication)
                {
                    Entity activityParty = new Entity("activityparty");
                    activityParty.Attributes.Add("partyid", new EntityReference("contact", ((Guid)recipient.Attributes["contactid"])));

                    Entity communicationActivity = new Entity(entityToUse);

                    communicationActivity.Attributes.Add("subject", campComm.Attributes["subject"].ToString());
                    communicationActivity.Attributes.Add("to", activityParty);
                    communicationActivity.Attributes.Add("description", "Campaign Communication Generated Activity.");
                    communicationActivity.Attributes.Add("regardingobjectid", new EntityReference("contact", ((Guid)recipient.Attributes["contactid"])));
                    communicationActivity.Attributes.Add("ownerid", new EntityReference("systemuser", ((EntityReference)campComm.Attributes["ownerid"]).Id));

                    service.Create(communicationActivity);

                    Thread.Sleep(1000);
                }
            }
            catch (SoapException ex)
            {
                WriteMsg(String.Format("SoapEx: {0}", ex.Detail.InnerText));
                WriteMsg(ex.StackTrace);
            }
            catch (Exception ex)
            {
                WriteMsg(String.Format("Ex: {0}", ex.Message));
                WriteMsg(ex.StackTrace);
            }
        }

        private void WriteMsg(string message)
        {
            Trace.TraceInformation("{0} - {1}", DateTime.Now.ToString("yyyy/MM/dd H:mm:ss"), message);
        }
    }

Wednesday, 14 May 2014

Get all Atrributes in MS CRM2011

var attributes = Xrm.Page.data.entity.attributes.get();
 
for (var i in attributes) {
 
attributes[i].setSubmitMode("never");
 
}

Xrm.Page.ui.close();



Aim: To close the CRM form window using javascript when the user saves the form for a particular condition. 
Xrm.Page.ui.close();

This method closes the current form in which it is getting called. If any unsaved information is found, it prompts the user to save the changes prior to closing it.

If you don't want to show the prompt to the user you need to set submitMode to "never"
Below is the code snippet : 


Tuesday, 13 May 2014

QueryExpressionMSCRM

 QueryExpression query = new QueryExpression()
        {
            EntityName = "contact",
            ColumnSet = new ColumnSet("contactid"),
            Criteria =
            {
                Conditions =
                                {
                                    new ConditionExpression("dpo_username",ConditionOperator.Equal,TextBox1.Text),
                                    new ConditionExpression("demo_password",ConditionOperator.Equal,TextBox2.Text),
                                }
            }
        };


        EntityCollection entityCollection = _service.RetrieveMultiple(query);

f(entity.Attributes.Contains("money_field1"))
{
a=((Money)entity.Attributes["money_field1"]).Value;
}
if(entity.Attributes.Contains("money_field2"))
{
b=((Money)entity.Attributes["money_field2"]).Value;
}




 string fetchxmlContact = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                            <entity name='contact'>
                                            <attribute name='fullname' />
                                            <attribute name='telephone1' />
                                            <attribute name='contactid' />
                                            <attribute name='lastname' />
                                            <attribute name='demo_username' />
                                            <attribute name='firstname' />
                                            <order attribute='fullname' descending='false' />
                                            <filter type='and'>
                                            <condition attribute='demo_username' operator='eq' value='" + userName + "' /><condition attribute='demo_password' operator='eq' value='" + password + "' /></filter></entity></fetch>";

                EntityCollection contactCollection = service.RetrieveMultiple(new FetchExpression(fetchxmlContact));

Customworkflows

public class SendEmail : CodeActivity
    {
        public static DependencyProperty EmailLookupProperty = DependencyProperty.Register("EmailLookup", typeof(EntityReference), typeof(SendEmail));

        [Input("Email to send:")]
        [ReferenceTarget("email")]
        public InArgument<EntityReference> EmailLookup
        {
            get;
            set;
        }

        protected override void Execute(CodeActivityContext executionContext)
        {
            if (executionContext == null)
            {
                throw new InvalidPluginExecutionException("Context is Null");
            }

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
            IWorkflowContext workflowContext = executionContext.GetExtension<IWorkflowContext>();
            IOrganizationService crmService = serviceFactory.CreateOrganizationService(workflowContext.UserId);

            // Create a SendEmail request.
            SendEmailRequest req = new SendEmailRequest();
            req.EmailId = EmailLookup.Get<EntityReference>(executionContext).Id;
            req.TrackingToken = string.Empty;
            req.IssueSend = true;

            // Send the email message.
            SendEmailResponse res = (SendEmailResponse)crmService.Execute(req);
        }
    }

ArtcleCreation

 EntityReference kbArticleTemplate = new EntityReference();
                kbArticleTemplate.LogicalName = "kbarticletemplate";
                kbArticleTemplate.Id = kbArticleTemplateId;    //Give KB Article template id here, for whichever template you want to create your KB.

                //Subject
                EntityReference kbArticleSubject = new EntityReference();
                kbArticleSubject.LogicalName = "subject";
                kbArticleSubject.Id = articleSubjectGuid;        //Give Subject Id here

                kbArticle.Attributes.Add(new KeyValuePair<string, object>("kbarticletemplateid", kbArticleTemplate));
                kbArticle.Attributes.Add(new KeyValuePair<string, object>("title", articleTitle));
                kbArticle.Attributes.Add(new KeyValuePair<string, object>("subjectid", kbArticleSubject));
                kbArticle.Attributes.Add(new KeyValuePair<string, object>("description", "Some Description"));
               // kbArticle.Attributes.Add(new KeyValuePair<string, object>("keywords",));
                //kbArticle.Attributes.Add(new KeyValuePair<string, object>("content", kbContent));
                kbArticle.Attributes.Add(new KeyValuePair<string, object>("articlexml", articleXml));
                Guid newTranlatedRecordId = organizationService.Create(kbArticle);    //Create the KB Article



                //Entity article = new Entity("kbarticle");
                //article["title"] = articleTitle;
                //article["subjectid"] = new EntityReference("subjectid", articleSubjectGuid);
                //article["articlexml"] = articleXml;
                //organizationService.Create(article);
            }
            catch (Exception)
            {
                throw;
            }
        }

        private string ParseArticleXml(string articleXml)
        {
            try
            {
                string strArticleXml = articleXml;
                XDocument doc1 = XDocument.Parse(articleXml);

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(articleXml);
                XmlElement root = doc.DocumentElement;

                XmlNodeList nodeList = doc.DocumentElement.SelectNodes(@"/articledata/section/content");
                foreach (XmlNode node in nodeList)
                {
                    if (node.ChildNodes[0] is XmlCDataSection)
                    {
                        XmlCDataSection cdataSection = node.ChildNodes[0] as XmlCDataSection;
                        if (cdataSection != null)
                        {
                            string cdataText = cdataSection.Value;
                            if (!string.IsNullOrEmpty(cdataText))
                            {
                                string translatedText = TranslateData(cdataText, toLanguage, clientID, clientSecret, detectmethoduri, endpointaddress);
                                if (!string.IsNullOrEmpty(translatedText))
                                {
                                    strArticleXml = strArticleXml.Replace(cdataText, translatedText);
                                }
                            }
                        }
                    }
                }
                return strArticleXml;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }



        private static void InitializeTranslationParameters(IOrganizationService service)
        {
            QueryExpression qe = new QueryExpression();
            qe.EntityName = "new_crmbingtranslatorconfig";
            qe.ColumnSet = new ColumnSet();
            qe.ColumnSet.Columns.Add("new_entityname");
            qe.ColumnSet.Columns.Add("new_clientid");
            qe.ColumnSet.Columns.Add("new_clientsecret");
            qe.ColumnSet.Columns.Add("new_detectmethoduri");
            qe.ColumnSet.Columns.Add("new_endpointaddress");
            qe.ColumnSet.Columns.Add("new_outputlanguage");

            ConditionExpression ce = new ConditionExpression();
            ce.AttributeName = "new_entityname";
            ce.Operator = ConditionOperator.Equal;
            ce.Values.Add("MAIN_CONFIGURATION");

            FilterExpression fe = new FilterExpression();
            fe.Conditions.Add(ce);
            qe.Criteria.AddFilter(fe);

            EntityCollection ec = service.RetrieveMultiple(qe);
            foreach (Entity config in ec.Entities)
            {
                clientID = config["new_clientid"].ToString();
                clientSecret = config["new_clientsecret"].ToString();
                detectmethoduri = config["new_detectmethoduri"].ToString();
                endpointaddress = config["new_endpointaddress"].ToString();
                toLanguage = config["new_outputlanguage"].ToString();
            }
        }

FaceBookposts in MS CRM

public class DynamicsCRM
    {
        OrganizationServiceProxy orgService;

        public void RegisterFacebookPost(string User, string Text, string Term, string OriginalFacebookPostDate, DateTime FacebookPostDate, string ProfileURL)
        {
            try
            {
                ClientCredentials credentials = new ClientCredentials();
                credentials.UserName.UserName = ConfigurationManager.AppSettings["UserName"];
                credentials.UserName.Password = ConfigurationManager.AppSettings["Password"];
                ClientCredentials deviceCredentials = new ClientCredentials();
                deviceCredentials.UserName.UserName = ConfigurationManager.AppSettings["DeviceUserName"];
                deviceCredentials.UserName.Password = ConfigurationManager.AppSettings["DevicePassword"];
                Uri organizationUri = new Uri(ConfigurationManager.AppSettings["OrganizationURL"]);
                Uri homeRealmUri = null;
                orgService = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, deviceCredentials);

                Entity FacebookPost = new Entity("new_facebookpost");
                FacebookPost["new_user"] = User;
                FacebookPost["new_text"] = Text;
                FacebookPost["new_term"] = Term;
                FacebookPost["new_originalfacebookpostdate"] = OriginalFacebookPostDate;
                FacebookPost["new_facebookpostdate"] = FacebookPostDate;
                FacebookPost["new_profileurl"] = ProfileURL;
                //FacebookPost["new_facebookpostid"] = FacebookPostId;

                orgService.Create(FacebookPost);
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        public string CheckLastfacebookPost(string Term)
        {
            try
            {
                ClientCredentials credentials = new ClientCredentials();
                credentials.UserName.UserName = ConfigurationManager.AppSettings["UserName"];
                credentials.UserName.Password = ConfigurationManager.AppSettings["Password"];
                ClientCredentials deviceCredentials = new ClientCredentials();
                deviceCredentials.UserName.UserName = ConfigurationManager.AppSettings["DeviceUserName"];
                deviceCredentials.UserName.Password = ConfigurationManager.AppSettings["DevicePassword"];
                Uri organizationUri = new Uri(ConfigurationManager.AppSettings["OrganizationURL"]);
                Uri homeRealmUri = null;
                orgService = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, deviceCredentials);
                QueryExpression query = new QueryExpression("new_facebookpost");
                query.ColumnSet.AddColumns("new_facebookpostdate", "new_term", "new_originalfacebookpostdate");
                query.Criteria = new FilterExpression();
                query.Criteria.AddCondition("new_term", ConditionOperator.Equal, Term);
                EntityCollection results = orgService.RetrieveMultiple(query);
                return results.Entities.Max(g => g.Attributes["new_originalfacebookpostdate"].ToString());
            }
            catch (Exception ex)
            {
                return "0";
            }
        }
    }

queryExpression

 QueryExpression query = new QueryExpression("demo_supplierconfiguration");
                query.ColumnSet = new ColumnSet() { AllColumns = false };
                query.ColumnSet.AddColumns("demo_supplierid", "demo_stationid", "demo_commodityid");
                query.Criteria = new FilterExpression() { FilterOperator = LogicalOperator.And };              
                query.Criteria.Conditions.Add(new ConditionExpression("demo_supplierconfigurationid", ConditionOperator.Equal, preImage.GetAttributeValue<EntityReference>("demo_configurationid").Id));
                EntityCollection collection = service.RetrieveMultiple(query);
                if(collection.Entities.Count > 0)
                {
                    Entity config = collection.Entities[0];

                    supplierId = config.GetAttributeValue<EntityReference>("demo_supplierid") != null ? config.GetAttributeValue<EntityReference>("demo_supplierid").Id : Guid.Empty;
                    stationId = config.GetAttributeValue<EntityReference>("demo_stationid") != null ? config.GetAttributeValue<EntityReference>("demo_stationid").Id : Guid.Empty;
                    commodityId = config.GetAttributeValue<EntityReference>("demo_commodityid") != null ? config.GetAttributeValue<EntityReference>("demo_commodityid").Id : Guid.Empty;


foreach (var items in result.Entities)
        {
            string date = items.GetAttributeValue<DateTime>("followupby").ToString();
            if (items.Attributes.Contains("customerid"))
            {
            string names = (items["customerid"] as EntityReference).Id.ToString();
            }
           // string Name = (items.Attributes["customerid"] as EntityReference).Id.ToString();

            string optional = items.FormattedValues["casetypecode"];
            string code = (items.FormattedValues.Contains("casetypecode") ? items.FormattedValues["casetypecode"] : "Ambiguous");
        }

plugin to call externalWebservice

 public class PushToFacebook : IPlugin
    {

        /// <summary>
        /// Standard execute method of a plugin.
        /// </summary>
        /// <param name="serviceProvider">Service Provider containing CRM endpoints</param>
        public void Execute(IServiceProvider serviceProvider)
        {
            string message = string.Empty;
            string postId = string.Empty;
            Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
            serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));

            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity)
            {
                Entity entity = (Entity)context.InputParameters["Target"];
                if (entity.LogicalName == "new_post")
                {
                    if (entity.Attributes.Contains("new_message") && entity.Attributes.Contains("new_commentid"))
                    {
                        message = entity.Attributes["new_message"].ToString();
                        postId = entity.Attributes["new_commentid"].ToString();
                        this.Process(message, postId);
                    }
                    else
                    {
                        throw new Exception("The comment has not been logged ");
                    }
                }
            }
        }

        /// <summary>
        /// Method for posting back post to CRM
        /// </summary>
        /// <param name="message">Message to be posted</param>
        /// <param name="postId">Postid which is to be posted</param>
        private void Process(string message, string postId)
        {
            try
            {
                BasicHttpBinding myBinding = new BasicHttpBinding();
                myBinding.Name = "BasicHttpBinding_IService1";
                myBinding.Security.Mode = BasicHttpSecurityMode.None;
                myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
                myBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
                myBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
                EndpointAddress endPointAddress = new EndpointAddress("http://b3d1b7d74b504ecda951f061bff5e17c.cloudapp.net/PostToFacebookService.svc");
                PushToFacebookService.FacebookServiceClient client = new PushToFacebookService.FacebookServiceClient(myBinding, endPointAddress);
                client.SendToFacebook(postId, message);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}

HttpRequest For Xml data

function readXML() {
    var xmlPath = "../WebResources/CloneConfiguration";
    var xmldoc = new ActiveXObject("Microsoft.XMLDOM");
    xmldoc.preserveWhiteSpace = true;
    xmldoc.async = false;
    xmldoc.load(xmlPath);
    return xmldoc.xml;
}

var JScriptWebResourceUrl = "../WebResources/raj_xrmhelper";
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlHttp.open("GET", JScriptWebResourceUrl, false);
xmlHttp.send();
eval(xmlHttp.responseText);

function onClick() {
    try {
        var xmlPath = "../WebResources/raj_CloneConfiguration";
        $.ajax({
            type: "GET",
            url: xmlPath,
            dataType: "xml",
            success: pareseXML
        });
    } catch (e) {
        alert("Error while reading \"Clone Configuration XML\" file; Description - " + e.description);
        alert("Make sure you add JQuery & Json helper scripts to source entity form");
    }
}

Monday, 12 May 2014

IFRAME TO Dynamic URl

Name 
Specify a unique name.
In Javascript We write
function GetOrgName() {

  Xrm.Page.getControl('IFRAME_DemoIframe').setSrc("/WebResources/new_/html/Demo.html");


}
EntityForm:OnloadEvent Write that:


HTML to XRM Script

<html><head>
    <title></title>
    <script type="text/javascript">
        function test() {


                 var name = window.parent.Xrm.Page.getAttribute("name").getValue();
            var txtvalue = document.getElementById("demo");
            txtvalue.value = name;

//GetOrg() is javascript Functions In Webresource in MS CRM
window.parent.GetOrg();



        }
    </script>


<meta><meta><meta></head>
<body onload="test();" style="word-wrap: break-word;">

<input type="text" id="demo" name="fname"><br>







</body></html>

Sunday, 11 May 2014

QualifiedLead usingsoap

function QualifyLead() {
QualifyLeadRequest();
}
function QualifyLeadRequest() {
// debugger;
var leadid = Xrm.Page.data.entity.getId();
var xml = "" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + Xrm.Page.context.getAuthenticationHeader() + "<soap:Body><Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
"<request i:type=\"b:QualifyLeadRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">" +
"<a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">" +
"<a:KeyValuePairOfstringanyType><c:key>LeadId</c:key><c:value i:type=\"a:EntityReference\"><a:Id>" + leadid + "</a:Id><a:LogicalName>lead</a:LogicalName>" +
"<a:Name i:nil=\"true\"/></c:value></a:KeyValuePairOfstringanyType><a:KeyValuePairOfstringanyType>" +
"<c:key>CreateAccount</c:key><c:value i:type=\"d:boolean\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">true</c:value></a:KeyValuePairOfstringanyType>" +
"<a:KeyValuePairOfstringanyType><c:key>CreateContact</c:key><c:value i:type=\"d:boolean\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">false</c:value></a:KeyValuePairOfstringanyType>" +
"<a:KeyValuePairOfstringanyType><c:key>CreateOpportunity</c:key><c:value i:type=\"d:boolean\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">false</c:value></a:KeyValuePairOfstringanyType>" +
"<a:KeyValuePairOfstringanyType><c:key>Status</c:key><c:value i:type=\"a:OptionSetValue\"><a:Value>3</a:Value></c:value></a:KeyValuePairOfstringanyType>" +
"</a:Parameters><a:RequestId i:nil=\"true\"/><a:RequestName>QualifyLead</a:RequestName></request></Execute></soap:Body></soap:Envelope>" +
"";
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
var serverUrl = Xrm.Page.context.getOrgUniqueName() + "/XRMServices/2011/Organization.svc/web";
xmlHttpRequest.Open("POST", serverUrl, false);
xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Accept", "application/xml, text/xml, */*");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.onreadystatechange = function () { QualifyLeadResponse(xmlHttpRequest, successCallback, null); };
xmlHttpRequest.send(xml);
//var resultXml = xmlHttpRequest.responseXML;
// alert(resultXml.xml);
}
function QualifyLeadResponse(req, successCallback, errorCallback) {
if (req.readyState == 4) {
if (req.status == 200) {
// alert("Lead Qualified");
}
else {
GetError(req.responseXML);
}
}
}


Odata EXamples in MS CRM

Single Retriew Examples Demos
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
function retrivedata()
{
var odataSelect = "https://jhanucrm.crm5.dynamics.com/xrmservices/2011/OrganizationData.svc/AccountSet?$filter=Name eq '995151'";
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataSelect,
beforeSend: function (XMLHttpRequest)
{ XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, XmlHttpRequest)
{
// Use only one of these two methods
// Use for a selection that may return multiple entities
///ProcessReturnedEntities(data.d.results);
// Use for a single selected entity
ProcessReturnedEntity(data.d);
},
error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + odataSelect); }
});
}
function ProcessReturnedEntity(a)
{
debugger;
alert(a);
}

function retrivedata()
{
var odataSelect = "https://jhanucrm.crm5.dynamics.com/xrmservices/2011/OrganizationData.svc/AccountSet?$filter=Name eq '995151'";
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataSelect,
beforeSend: function (XMLHttpRequest)
{ XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, XmlHttpRequest)
{
// Use only one of these two methods
// Use for a selection that may return multiple entities
///ProcessReturnedEntities(data.d.results);
// Use for a single selected entity
ProcessReturnedEntity(data.d);
},
error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + odataSelect); }
});
}
function ProcessReturnedEntity(a)
{
debugger;
alert(a);
}




Account Creation Examples
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
function LetterOnLoad() {
debugger;
var context = Xrm.Page.context;
var serverUrl = context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var CRMObject = new Object();
/////////////////////////////////////////////////////////////
// Specify the ODATA entity collection
var ODATA_EntityCollection = "/AccountSet";
/////////////////////////////////////////////////////////////
// Define attribute values for the CRM object you want created
CRMObject.Name = "TEST";
CRMObject.Telephone1 = "123";
CRMObject.Fax = "456";
//Parse the entity object into JSON
var jsonEntity = window.JSON.stringify(CRMObject);
//Asynchronous AJAX function to Create a CRM record using OData
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection,
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
alert("success");
var NewCRMRecordCreated = data["d"];
alert("CRM GUID created: " + NewCRMRecordCreated.AccountId);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("failure");
}
});
}



delect Examples in ContactSet Exaples in
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

function DeleteAccount() {
// Pass the guid of the account.
var accountId = '191E1ECD-500A-E211-B3FA-Q3E3B508F839';
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc/AccountSet";
var ODataPath = serverUrl + ODATA_ENDPOINT;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataPath + "(guid'" + accountId + "')",
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown);
}
});
}
updatingt Account Examples in in Odata
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

function UpdateAccount() {
var accountId = Xrm.Page.data.entity.getId();
var objAccount = new Object();
// set the name of Account
objAccount.Name = "Account Updated from jscript";
// set the Primary Contact lookup field
objAccount.PrimaryContactId = { Id: '{421E1EE5-500A-E211-B3FA-78E3B508F827}', LogicalName: "contact", Name: 'Adrian Dumitrascu (sample)' };
// set the Address Type optionset field
objAccount.Address1_AddressTypeCode = { Value: 2 };
// set the Credit Hold boolean field
objAccount.CreditOnHold = true;
// Parse the entity object into JSON
var jsonEntity = window.JSON.stringify(objAccount);
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc/AccountSet";
var ODataPath = serverUrl + ODATA_ENDPOINT;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataPath + "(guid'" + accountId + "')",
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown);
}
});
}

StartWorkflowDynamically

StartWorkflowDynamically = function (entityName, entityId, workFlowProcessID) {
entityName = "";
// var entityId = "3286F4FC-C435-E011-A258-00155D006B3F";
//var workFlowProcessID = "791b1070-adf3-49a5-a7ef-68836da0e806";
var xml = "" + "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:soap=\"" +
"http://schemas.xmlsoap.org/soap/envelope/\" " +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
Xrm.Page.context.getAuthenticationHeader() +
"<soap:Body>" +
"<Request xsi:type=\"ExecuteWFProcessRequest\" " +
"xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
"<ProcessId>" +
workFlowProcessID +
"</ProcessId>" +
"<EntityMoniker>" +
"<Id xmlns=\"http://schemas.microsoft.com/crm/2007/CoreTypes\">" +
entityId +
"</Id>" +
"<Name xmlns=\"http://schemas.microsoft.com/crm/2007/CoreTypes\">" +
entityName +
"</Name>" +
"</EntityMoniker>" +
"</Request>" +
"</soap:Body>" +
"</soap:Envelope>" +
"";
try {
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Execute");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);
}
catch (f) {
}
var resultXml = xmlHttpRequest.responseXML;
//alert(resultXml.text);
return resultXml.xml;
} // Start Workflow//
// Executed using CrmService.asmx
function StartWorkflow(entityName, entityId, workFlowProcessID) {
entityName = "";
//var entityId = "3286F4FC-C435-E011-A258-00155D006B3F";
//var workflowProcessId = "791b1070-adf3-49a5-a7ef-68836da0e806";//"8d14d034-5bb8-4a49-af9b-a08777cffaaa";
var xml = "" +
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
Xrm.Page.context.getAuthenticationHeader() +
"<soap:Body>" +
"<Execute xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
"<Request xsi:type=\"ExecuteWorkflowRequest\">" +
"<EntityId>" + entityId + "</EntityId>" +
"<WorkflowId>" + workflowProcessId + "</WorkflowId>" +
"</Request>" +
"</Execute>" +
"</soap:Body>" +
"</soap:Envelope>";
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Execute");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);
}
// Excuted using IOrganizationService (WCF)
function StartWorkflowDynamic(entityID,workflowID) {
//var entityID = Xrm.Page.data.entity.getId();
var currentEntity = "";
var url = Xrm.Page.context.getServerUrl();
var entityId = entityID;
var workflowId = workflowID;
var OrgServicePath = "/XRMServices/2011/Organization.svc/web";
url = url + OrgServicePath;
var request;
request = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<s:Body>" +
"<Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
"<request i:type=\"b:ExecuteWorkflowRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">" +
"<a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">" +
"<a:KeyValuePairOfstringanyType>" +
"<c:key>EntityId</c:key>" +
"<c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">" + entityId + "</c:value>" +
"</a:KeyValuePairOfstringanyType>" +
"<a:KeyValuePairOfstringanyType>" +
"<c:key>WorkflowId</c:key>" +
"<c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">" + workflowId + "</c:value>" +
"</a:KeyValuePairOfstringanyType>" +
"</a:Parameters>" +
"<a:RequestId i:nil=\"true\" />" +
"<a:RequestName>ExecuteWorkflow</a:RequestName>" +
"</request>" +
"</Execute>" +
"</s:Body>" +
"</s:Envelope>";
var req = new XMLHttpRequest();
req.open("POST", url, true)
// Responses will return XML. It isn't possible to return JSON.
req.setRequestHeader("Accept", "application/xml, text/xml, */*");
req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
//req.onreadystatechange = function () { assignResponse(req); };
req.send(request);
}
function startworkfloe() {
var entityID = Xrm.Page.data.entity.getId();
var workflowID = "7f120af8-69fa-44bc-80a7-2ae1a33cbbe5";
var odataresult;
if (odataresultname == "workflowusing Javascript") {
var workflowID = workflowID;
}
StartWorkflowDynamic(entityID, workflowID);
}

Retrieving More than 50 records using OData in CRM 2011

relatedAccounts = [];
function onload() {
var serverUrl = Xrm.Page.context.getServerUrl();
var oDataUri = serverUrl + "/xrmservices/2011/OrganizationData.svc/AccountSet?$select=AccountId,AccountNumber&$filter=substringof('995151',AccountNumber)";
GetRecords(oDataUri);
var totalRecords = relatedAccounts.length;
}
function GetRecords(url) {
jQuery.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: url,
async: false,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (data && data.d != null && data.d.results != null) {
AddRecordsToArray(data.d.results);
FetchRecordsCallBack(data.d);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
alert("Error : has occured during retrieval of the records ");
}
});
}
function AddRecordsToArray(records) {
for (var i = 0; i < records.length; i++) {
relatedAccounts.push(records[i]);
}
}
function FetchRecordsCallBack(records) {
if (records.__next != null) {
var url = records.__next;
GetRecords(url);
}
}

Set notification2011

var Severity = { Info: 1, Warning: 2, Error: 3 };
// Disable notifications
function disableNotifications() {
$('.Notifications').parent().parent().hide();
}
// Enable notifications
function enableNotifications() {
$('.Notifications').parent().parent().show();
}
// Delete all notificanions
function deleteAllNotifications() {
$('.Notifications').empty();
}
// Set the color of notification area
function setNotificationsColor(color) {
$('.Notifications').css("background-color", color);
}
// Show custom notification
//
// Usage Example
// showNotification(
// 'Error occured<b style="COLOR: #ff0000">Custom Error.</b>',
// Severity.Error);
//
var Severity = { Info: 1, Warning: 2, Error: 3 };
function showNotification(messageHtml, severity) {
var css = "ms-crm-ImageStrip-notif_icn_warn16";
switch (severity) {
case 1:
css = "ms-crm-ImageStrip-notif_icn_info16";
break;
case 2:
css = "ms-crm-ImageStrip-notif_icn_warn16";
break;
case 3:
css = "ms-crm-ImageStrip-notif_icn_crit16";
break;
}
var html = '<div id="Notification" class="Notification"> \
<table cellspacing="0" cellpadding="0"> \
<tbody> \
<tr> \
<td valign="top"> \
<img class="' + css + '" alt="" \
src="/_imgs/imagestrips/transparent_spacer.gif"> \
</td> \
<td> \
<span id="Notification_text">'
+ messageHtml +
'</span> \
</td> \
</tr> \
</tbody> \
</table> \
</div>';
$('.Notifications').append(html);
}

function AddNotification(strMessage) {
var notificationsList = Sys.Application.findComponent('crmNotifications');
notificationsList.AddNotification('noteId1', 1, 'namespace', strMessage);
}
var strMessage = Xrm.Page.getAttribute('abcc_cources').getValue()
if (strMessage != "") {
strMessage = "The current Contact is " + strMessage;
AddNotification(strMessage);
}

filtered lookups using javascript

ActualCostAllocationLookup = function () {
var thisBE = new BusinessEntityCombo("", "");
thisBE = GetBusinessEntity();
if (thisBE.name == 'SIML') {
var lookupAttributeEntityName = "ledgera";
var lookupAttributeName = "ledgeraccountid";
var strFilterCondition = '<condition attribute="statecode" operator="eq" value="0"/>';
AddCustomFilterView(lookupAttributeEntityName, lookupAttributeName, strFilterCondition);
}
else {
var lookupAttributeEntityName = "ledgeraccount";
var lookupAttributeName = "edgeraccountid";
//var strFilterCondition = '<condition attribute="businessentityid" operator="eq" value="' + thisBE.id + '"/>';
//AddCustomFilterView(lookupAttributeEntityName, lookupAttributeName, strFilterCondition);
var fetchXMLInput = '<fetch mapping="logical"><entity name="ledgeraccount"><attribute name="name" /><attribute name="businessentityledgeraccountsid" /><attribute name="description" /><attribute name="ledgeraccountid" /><order attribute="name" /><link-entity name="businessentity" from="businessentityid" to="businessentityledgeraccountsid" alias="aa"><filter type="and"><condition attribute="businessentityid" operator="eq" value="' + thisBE.id + '" /></filter></link-entity></entity></fetch>';
AddCustomFilterViewCustom(lookupAttributeEntityName, lookupAttributeName, fetchXMLInput);
}

Custom filtered lookup

//Call from CategoryLvl1Id onchange event
CategoryLvl1Lookup = function () {
Xrm.Page.getAttribute("categorylevel2id").setValue(null); //clear field
if (Xrm.Page.getAttribute("categorylevel1id").getValue() != null) {
var id = Xrm.Page.getAttribute("i5_categorylevel1id").getValue()[0].id;
var lookupAttributeEntityName = "categorylevel2";
var lookupAttributeName = "categorylevel2id";
var viewDisplayName = "Filtered Records";
var viewId = Xrm.Page.getControl(lookupAttributeName).getDefaultView();
GetViewDetails(viewId);
var viewDisplayName = "Filtered Records";
var fetchXml = '<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false"> <entity name="categorylevel2"><all-attributes/><filter type="and"> <condition attribute="categorylevel1id" operator="eq" value="' + id + '" /> </filter> </entity></fetch>';
Xrm.Page.getControl("categorylevel2id").addCustomView(viewId, "categorylevel2", viewDisplayName, fetchXml, layoutXml, true);
}
SetTitle();

EMailFormats XRM

function SetEmailError(string) {
var EmailAddressError = document.getElementById("EmailAddressError");
if (EmailAddressError.hasChildNodes()) {
EmailAddressError.replaceChild(document.createTextNode(string), EmailAddressError.firstChild);
}
else {
EmailAddressError.appendChild(document.createTextNode(string));
}
}
function EmailAddressEntered() {
var enteredEmail = document.getElementById("EmailAddressTextBox").value;
var identityProvider = null;
if (enteredEmail.length === 0) {
SetEmailError("Please enter an e-mail address.");
return;
}
if (enteredEmail.indexOf("@") <= 0) {
SetEmailError("Please enter a valid e-mail address.");
return;
}
var enteredDomain = enteredEmail.split("@")[1].toLowerCase();
for (var i in identityProviders) {
for (var j in identityProviders[i].EmailAddressSuffixes) {
if (enteredDomain == identityProviders[i].EmailAddressSuffixes[j].toLowerCase()) {
identityProvider = identityProviders[i];
}
}
}
if (identityProvider === null) {
SetEmailError("'" + enteredDomain + "' is not a recognized e-mail domain.");
return;
}
// If we have gotten this far the e-mail address suffix was recognized. Write a cookie and redirect to the login URL.
SetCookie(identityProvider.Name);
window.location = identityProvider.LoginUrl;
}