javascript helper-程序员宅基地

ContractedBlock.gif ExpandedBlockStart.gif Code
Traditional Web Service Soap Request
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'>"+ 
authenticationHeader
+ 
"<soap:Body>"+ 
"<RetrieveMultiple xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>"+ 
"<query xmlns:q1='http://schemas.microsoft.com/crm/2006/Query'"+
" xsi:type='q1:QueryExpression'>"+ 
"<q1:EntityName>contact</q1:EntityName>"+ 
"<q1:ColumnSet xsi:type='q1:ColumnSet'>"+ 
"<q1:Attributes>"+ 
"<q1:Attribute>fullname</q1:Attribute>"+ 
"<q1:Attribute>contactid</q1:Attribute>"+ 
"</q1:Attributes>"+ 
"</q1:ColumnSet>"+ 
"<q1:Distinct>false</q1:Distinct>"+ 
"<q1:Criteria>"+ 
"<q1:FilterOperator>And</q1:FilterOperator>"+ 
"<q1:Conditions>"+ 
"<q1:Condition>"+ 
"<q1:AttributeName>address1_city</q1:AttributeName>"+ 
"<q1:Operator>Like</q1:Operator>"+ 
"<q1:Values>"+ 
"<q1:Value xsi:type='xsd:string'>"+searchCity+"</q1:Value>"+ 
"</q1:Values>"+ 
"</q1:Condition>"+ 
"</q1:Conditions>"+ 
"</q1:Criteria>"+ 
"</query>"+ 
"</RetrieveMultiple>"+ 
"</soap:Body>"+ 
"</soap:Envelope>";

This code is only the SOAP body generation.  It doesn
't even include the HTTP request or extracting the data.  You can imagine what a maintenance nightmare you have when your form requires multiple web service calls.  Wouldn't it be nice if the API was closer to the .NET SDK API?

Helper Objects
I have written a couple of helper classes to help make life easier. Here are two examples of what you can 
do with the helper classes. It doesn't currently support everything (grouping multiple levels of filter conditions), but it handles 90% of the cases you run into. As I add more functionality to the clases, I will repost them. 

Note:  The blog likes to reformat the code.  You can download a code file below. 

Simple query on one entity 
This query does a simple select of leads where the city is either Bloomington or Minneapolis.   Include this code as well as the helper objects from the bottom of the post.
var LOGICAL_OPERATOR_OR = "Or";
var CONDITION_OPERATOR_EQUAL = "Equal"; 

// Create object passing in the entity you are selecting from      
var crmService = new CrmService("lead", LOGICAL_OPERATOR_OR);
crmService.AddColumn("fullname");
crmService.AddColumn("leadid");

// Add filter conditions  (note:  the "OR" logical operator was specified in constructor)
crmService.AddFilterCondition("address1_city", "Bloomington", CONDITION_OPERATOR_EQUAL);
crmService.AddFilterCondition("address1_city", "Minneapolis", CONDITION_OPERATOR_EQUAL);

// Retrieve the result object
var result = crmService.RetrieveMultiple();

// Loop through rows and select values (they return strings) 
for (rowsNumber in result.Rows) {
   var row = result.Rows[rowsNumber];
   // Get Column By Name
   alert(row.GetValue("fullname"));
   alert(row.GetValue("leadid"));
}

Query that Links in Multiple Tables 
This selects accountnumber, accountid, and name from the account entity by specifying the ID of the contact.  Include this code as well as the helper objects from the bottom of the post.
var LOGICAL_OPERATOR_AND = "And";
var LOGICAL_OPERATOR_OR = "Or";
var CONDITION_OPERATOR_EQUAL = "Equal";
var JOINOPERATOR_INNER = "Inner";

// Create object passing in the entity you are selecting from       
var crmService = new CrmService("account", LOGICAL_OPERATOR_OR);

// Specify select columns
crmService.AddColumn("accountnumber");
crmService.AddColumn("accountid");
crmService.AddColumn("name");

// Define linked entity - similar to SDK overload
var entityLinked = crmService.AddLinkedEntityCondition("account", "contact", "accountid", "parentcustomerid", JOINOPERATOR_INNER)

// Set filter operator (AND, OR, Ect)
entityLinked.FilterOperator = LOGICAL_OPERATOR_AND;

// Add filter condition (can add as multiple)
entityLinked.AddFilterCondition("contactid", "{BB1F590A-37D0-DC11-AA32-0003FF33509E}", CONDITION_OPERATOR_EQUAL);

// Retrieve the result object
var result = crmService.RetrieveMultiple();

// Loop through rows and select values (they return strings)
for (rowsNumber in result.Rows) {
   var row = result.Rows[rowsNumber];
   // Get Column By Name
   alert(row.GetValue("accountnumber"));
   alert(row.GetValue("name"));
   alert(row.GetValue("accountid"));
}

Helper Objects - Simply copy into the top of your form load 
var LOGICAL_OPERATOR_AND = "And";
var LOGICAL_OPERATOR_OR = "Or";
var CONDITION_OPERATOR_LIKE = "Like";
var CONDITION_OPERATOR_EQUAL = "Equal";
var CONDITION_OPERATORNOT_EQUAL = "NotEqual";
var JOINOPERATOR_INNER = "Inner";
var JOINOPERATOR_LEFTOUTER = "LeftOuter";
var JOINOPERATOR_NATURAL = "Natural";


function CrmService(entityName, logicalOperator) {
    // Double check in case you pass a variable that hasn
't been set
    
// This error is hard to track down
    if (logicalOperator == null)
        
throw new Error("Must specify non-null value for logicalOperator");

    
if (entityName == null)
        
throw new Error("Must specify non-null value for entityName");
    
this.entityName = entityName;
    
this.ColumnSet = new Array();
    
this.LogicalOperator = logicalOperator;
    
this.Conditions = new Array();
    
this.LinkedEntities = new Array();
}


CrmService.prototype.getEntityName 
= function() {
    
return this.entityName;
}

function Condition(field, value, operator) {
    
this.Field = field;
    
this.Value = CrmEncodeDecode.CrmXmlEncode(value);
    
// Double check in case you pass a variable that hasn't been set
    // This error is hear to track down
    if (operator == null)
        
throw new Error("Must specify non-null value for operator");
    
this.Operator = operator;
}

CrmService.prototype.setEntityName 
= function() {
    
return this.entityName;
}

CrmService.prototype.AddColumn 
= function(columnName) {
    
this.ColumnSet[this.ColumnSet.length] = columnName;
}

CrmService.prototype.AddFilterCondition 
= function(field, value, conditionOperator) {
    
this.Conditions[this.Conditions.length] = new Condition(field, value, conditionOperator);
}


function LinkedEntity(linkFromEntityName, linkToEntityName, linkFromAttributeName, linkToAttributeName, joinOperator) {
    
this.LinkFromEntityName = linkFromEntityName;
    
this.LinkToEntityName = linkToEntityName;
    
this.LinkFromAttributeName = linkFromAttributeName;
    
this.LinkToAttributeName = linkToAttributeName;
    
if (joinOperator == null)
        
throw new Error("Must specify non-null value for operator");
    
this.JoinOperator = joinOperator;
    
this.Conditions = new Array();
    
this.FilterOperator = LOGICAL_OPERATOR_AND;
}

LinkedEntity.prototype.AddFilterCondition 
= function(field, value, conditionOperator) {
    
this.Conditions[this.Conditions.length] = new Condition(field, value, conditionOperator);
    
return this.Conditions[this.Conditions.length - 1];
}

CrmService.prototype.AddLinkedEntityCondition 
= function(linkFromEntityName, linkToEntityName, linkFromAttributeName, linkToAttributeName, joinOperator) {
    
this.LinkedEntities[this.LinkedEntities.length] = new LinkedEntity(linkFromEntityName, linkToEntityName, linkFromAttributeName, linkToAttributeName, joinOperator);
    
return this.LinkedEntities[this.LinkedEntities.length - 1];
}

function RetrieveMultipleResult(crmService) {
    
this.Rows = new Array();
    
this.CrmService = crmService;
}


RetrieveMultipleResult.prototype.AddRow 
= function() {
    
this.Rows[this.Rows.length] = new Row();
    
return this.Rows[this.Rows.length - 1];
}

 

function Row() {
    
this.Columns = new Array();
}

function Column(columnName, value, dataType) {
    
this.ColumnName = columnName;
    
this.Value = value;
    
this.DataType = dataType;
}

Row.prototype.AddColumn 
= function(columnName, value) {
    
this.Columns[this.Columns.length] = new Column(columnName, value);
}

Row.prototype.GetColumn 
= function(columnName) {
    
for (columnNumber in this.Columns) {
        
var column = this.Columns[columnNumber];
        
if (columnName.toLowerCase() == column.ColumnName.toLowerCase())
            
return column;
    }
    
throw new Error("Column " + columnName + " does not exist");
}

Row.prototype.GetValue 
= function(columnName) {
    
var column = this.GetColumn(columnName);
    
return column.Value;
}


CrmService.prototype.RetrieveMultiple 
= function() {

    
//create SOAP envelope
    var xmlSoapHeader = "" +
"<?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\">";

    
var xmlAuthHeader = GenerateAuthenticationHeader();

    
var xmlSoapBody = "<soap:Body>" +
 
"      <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">  " +
 "<query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">  " +
 "  <q1:EntityName>" + this.getEntityName() + "</q1:EntityName>  " +
 
"  <q1:ColumnSet xsi:type=\"q1:ColumnSet\">  " +
 
"    <q1:Attributes>  ";

    
for (columnNumber in this.ColumnSet) {
        
var column = this.ColumnSet[columnNumber];
        xmlSoapBody 
= xmlSoapBody + "          <q1:Attribute>" + column + "</q1:Attribute>";
    }

    xmlSoapBody 
= xmlSoapBody + "        </q1:Attributes>" +
 
"      </q1:ColumnSet>" +
 
"          <q1:Distinct>false</q1:Distinct>  " +
 
"          <q1:PageInfo>  " +
 
"            <q1:PageNumber>0</q1:PageNumber>  " +
 
"            <q1:Count>0</q1:Count>  " +
 
"          </q1:PageInfo>  " +
 
"         <q1:LinkEntities>";

    
if (this.LinkedEntities.length > 0) {
        
for (linkedEntityNumber in this.LinkedEntities) {
            
var linkedEntity = this.LinkedEntities[linkedEntityNumber];
            xmlSoapBody 
+= " <q1:LinkEntity> ";
            xmlSoapBody 
+= "                 <q1:LinkFromAttributeName>" + linkedEntity.LinkFromAttributeName + "</q1:LinkFromAttributeName> ";
            xmlSoapBody 
+= "                 <q1:LinkFromEntityName>" + linkedEntity.LinkFromEntityName + "</q1:LinkFromEntityName> ";
            xmlSoapBody 
+= "                 <q1:LinkToEntityName>" + linkedEntity.LinkToEntityName + "</q1:LinkToEntityName> ";
            xmlSoapBody 
+= "<q1:LinkToAttributeName>" + linkedEntity.LinkToAttributeName + "</q1:LinkToAttributeName> ";
            xmlSoapBody 
+= "<q1:JoinOperator>" + linkedEntity.JoinOperator + "</q1:JoinOperator> ";
            xmlSoapBody 
+= "<q1:LinkCriteria> ";

            
if (linkedEntity.FilterOperator == null)
                
throw new Error("Must specify non-null value for FilterOperator");

            xmlSoapBody 
+= " <q1:FilterOperator>" + linkedEntity.FilterOperator + "</q1:FilterOperator> ";
            xmlSoapBody 
+= " <q1:Conditions> ";

            
for (conditionLinkedNumber in linkedEntity.Conditions) {
                
var conditionLinked = linkedEntity.Conditions[conditionLinkedNumber];
                xmlSoapBody 
+= "                             <q1:Condition> ";
                xmlSoapBody 
+= "                                             <q1:AttributeName>" + conditionLinked.Field + "</q1:AttributeName> ";
                xmlSoapBody 
+= "                                             <q1:Operator>" + conditionLinked.Operator + "</q1:Operator> ";
                xmlSoapBody 
+= "                                             <q1:Values> ";
                xmlSoapBody 
+= "                                                             <q1:Value xsi:type=\"xsd:string\">" + conditionLinked.Value + "</q1:Value> ";
                xmlSoapBody 
+= "                                             </q1:Values> ";
                xmlSoapBody 
+= "                             </q1:Condition> ";
            }
            xmlSoapBody 
+= " </q1:Conditions> ";
            xmlSoapBody 
+= " <q1:Filters /> ";
            xmlSoapBody 
+= "</q1:LinkCriteria> ";
            xmlSoapBody 
+= "<q1:LinkEntities />";
            xmlSoapBody 
+= "</q1:LinkEntity>";
        }
    }

    
if (this.LogicalOperator == null)
        
throw new Error("Must specify non-null value for LogicalOperator");


    xmlSoapBody 
+= "</q1:LinkEntities>" +
 
"          <q1:Criteria>  " +
 
"            <q1:FilterOperator>" + this.LogicalOperator + "</q1:FilterOperator>  " +
 
"            <q1:Conditions>  ";

 

    
for (conditionNumber in this.Conditions) {
        
var condition = this.Conditions[conditionNumber];

        
if (condition.Operator == null)
            
throw new Error("Must specify non-null value for condition Operator");

        xmlSoapBody 
+= "              <q1:Condition>  " +
                
"                <q1:AttributeName>" + condition.Field + "</q1:AttributeName>  " +
                
"                <q1:Operator>" + condition.Operator + "</q1:Operator>  " +
                
"                <q1:Values>  " +
                
"                  <q1:Value xsi:type=\"xsd:string\">" + condition.Value + "</q1:Value>  " +
                
"                </q1:Values>  " +
                
"              </q1:Condition>  ";

    }

 


    xmlSoapBody 
+= "            </q1:Conditions>  " +
 
"            <q1:Filters />  " +
 
"          </q1:Criteria>  " +
 
"          <q1:Orders />  " +
 
"        </query>  " +
 
"      </RetrieveMultiple>  " +
 
"    </soap:Body> " +
 
"   </soap:Envelope>";


    
var xmlt = xmlSoapHeader + xmlAuthHeader + xmlSoapBody;
    
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    xmlHttpRequest.Open(
"POST""/mscrmservices/2007/CrmService.asmx"false);
    xmlHttpRequest.setRequestHeader(
"SOAPAction""http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
    xmlHttpRequest.setRequestHeader(
"Content-Type""text/xml; charset=utf-8");
    xmlHttpRequest.setRequestHeader(
"Content-Length", xmlt.length);
    xmlHttpRequest.send(xmlt);

    
if (xmlHttpRequest.responseXML == null || xmlHttpRequest.responseXML.xml == null || xmlHttpRequest.responseXML.xml == "") {
        
if (xmlHttpRequest.responseText != null && xmlHttpRequest.responseText != "")
            
throw new Error(xmlHttpRequest.responseText);
        
else
            
throw new Error("Error returning response");
    }

    
var xmlResponse = xmlHttpRequest.responseXML.xml;
    
if (xmlHttpRequest.responseXML.documentElement.selectNodes("//error/description").length > 0) {
        
throw new Error(xmlResponse);
    }

    
var objNodeList = xmlHttpRequest.responseXML.documentElement.selectNodes("//BusinessEntity");


    
var totalNodesCount = objNodeList.length;

    
var result = new RetrieveMultipleResult(this);

    
var nodeIndex = 0;
    
var fieldTextTemp = "";
    
var fieldText = "";
    
if (totalNodesCount > 0) {
        
do {

            
var row = result.AddRow();
            
for (columnNumber in this.ColumnSet) {
                
var columnName = this.ColumnSet[columnNumber];
                fieldText 
= "";
                
var valueNode = objNodeList[nodeIndex].getElementsByTagName("q1:" + columnName)[0];
                
if (valueNode != null) {
                    fieldTextTemp 
= valueNode.childNodes[0].nodeValue;
                    
if (fieldTextTemp != null && fieldTextTemp != "") {
                        fieldText 
= fieldText + fieldTextTemp;
                    }
                }
                row.AddColumn(columnName, fieldText);
            }
            nodeIndex 
= nodeIndex + 1;
        }
        
while (totalNodesCount > nodeIndex)
    }
    
return result;
}

转载于:https://www.cnblogs.com/janmson/archive/2009/09/16/1567945.html

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_30675967/article/details/99630554

智能推荐

登录注册页面,JS判断用户手机号码是否已经存在,或者格式不正确_网页怎么验证电话号码是否存在-程序员宅基地

文章浏览阅读1.2w次,点赞3次,收藏37次。现在的网站使用手机号码注册的越来越多,这就涉及到要在登录注册页面,判断用户手机号码是否已经存在,或者格式不正确,最近的系统里面正好遇到了,已经实现成功,在这里记录一下如果电话号码已经存在,页面:如果电话格式不正确,页面:只有完全成功,符合规则,并且在没有被注册的情况下,才能注册成功页面如上,现在放代码:这个号码的验证,我主要放在js里面AJAX请求里面,现在放js..._网页怎么验证电话号码是否存在

JVM的StackMapTable的前世今生-程序员宅基地

文章浏览阅读2.3k次。在Java 6版本之后JVM在class文件中引入了栈图(StackMapTable)。作用为了提高JVM在类型检查的验证过程的效率栈图结构位于Code属性(指Classfile的Code属性)的属性表( attributes table)结构中。在字节码的Code属性中最多包含一个StackMapTable属性。在Java 7版本之后把栈图作为字节码文件中的强制部分。 本来程序员是不..._stackmaptable

c语言实训 选择结构程序设计,实验3 程序流程设计——选择结构程序设计.doc-程序员宅基地

文章浏览阅读280次。实验3 程序流程设计——选择结构程序设计淮海工学院计算机科学系实验报告书课程名:《 C语言程序设计A 》题 目: 实验2 程序流程设计—— 选择结构程序设计班 级: 软嵌151学 号: 2015123349姓 名: 陈正宁实验内容或题目编写一个程序,输入一个字母,若为大写字母,将其转换为小写字母后输出,否则原样输出..._c语言选择结构的应用实训目地

中断异常的分析思路_sensor采集中断-程序员宅基地

文章浏览阅读517次。工作学习中经常遇到中断相关的issue,我一般会从 中断源 (ic)-- 驱动层 -- SDK 逐层分析。往往解决的比较快。举一个例子,下面给出分析过程。问题描述: 开机过程中指纹driver有大量异常中断触发log 问题分析: 首先,我们要确定的是,这些异常中断是怎么来的。有以下三种case。 1.软件误报2.cpu主动发出的信号3.指纹sensor发出的信号 针对软件误报,只需要 cat ..._sensor采集中断

斧子的HTML5输出是什么,CF斧有什么使用技巧 斧子使用经验分享【详解】-程序员宅基地

文章浏览阅读82次。很多人知道斧子很牛,但就是用不好,所以好多人练了一段时间就放弃了,其实斧子练习有一些问题是需要注意的,下面就结合一下我个人练习斧子的经验,和大家分享一下,希望能对大家的练习提供一些帮助。1.拿起斧子要有信心和决心因为斧子有无视头盔的特点,所以面对其他武器,不应该有任何畏惧的心理(当然不能傻傻的向前冲然后白白送死),就像阿卡选手一样,要有一击毙命的信心和决心,因为在刀战战场上,心态很重要。有一个好的...

nginx配合fastdfs使用-----python上传测试_fastdfs python 上传-程序员宅基地

文章浏览阅读176次。开始前需要先准备好fdfs的环境https://blog.csdn.net/weixin_44834666/article/details/105686059一、安装py3Fdfs包pip install py3Fdfs二、编辑py文件from fdfs_client.client import Fdfs_client, get_tracker_conf# 创建客户端 client...._fastdfs python 上传

随便推点

洛谷-P1010 幂次方_任何一个正整数都可以用 22 的幂次方表示。例如 137=2^7+2^3+2^0137=2 7 +2-程序员宅基地

文章浏览阅读241次。题目描述任何一个正整数都可以用22的幂次方表示。例如137=2^7+2^3+2^0137=27+23+20。同时约定方次用括号来表示,即a^bab可表示为a(b)a(b)。由此可知,137137可表示为2(7)+2(3)+2(0)2(7)+2(3)+2(0)进一步:7= 2^2+2+2^07=22+2+20(2^121用22表示),并且3=2+2^03=2+20。所以最后137137可表示为2(2(2)+2+2(0))+2(2+2(0))+2(0)2..._任何一个正整数都可以用 22 的幂次方表示。例如 137=2^7+2^3+2^0137=2 7 +2 3 +2

数据结构与算法学习笔记-程序员宅基地

文章浏览阅读10w+次,点赞2.3k次,收藏1.6w次。本文是王争老师的《算法与数据结构之美》的学习笔记,详细内容请看王争的专栏。有不懂的地方指出来,我做修改。数据结构与算法思维导图数据结构指的是“一组数据的存储结构”,算法指的是“操作数据的一组方法”。数据结构是为算法服务的,算法是要作用再特定的数据结构上的。最常用的数据结构预算法:数据结构:数组、链表、栈、队列、散列表、二叉树‘、堆、跳表、图、Tire树 算法: 递归..._数据结构与算法

28款GitHub最流行的开源机器学习项目_github 学习开源项目分类集合-程序员宅基地

文章浏览阅读1.8w次,点赞4次,收藏37次。28款GitHub最流行的开源机器学习项目(一):TensorFlow排榜首 readygo 浏览 673 2016-04-18 20:31:12机器学习开源githubTensorFlow摘要现在机器学习逐渐成为行业热门,经过二十几年的发展,机器学习得到了十分广泛的应用,如:数据挖掘、计算机视觉、自然语言处理、生物特征识别、搜索引擎、医学诊断、DNA序列测_github 学习开源项目分类集合

javamail发送邮件的简单实例-程序员宅基地

文章浏览阅读65次。今天学习了一下JavaMail,javamail发送邮件确实是一个比较麻烦的问题。为了以后使用方便,自己写了段代码,打成jar包,以方便以后使用。呵呵以下三段代码是我的全部代码,朋友们如果想用,直接复制即可。第一个类:MailSenderInfo.javapackage com.util.mail;/** * 发送邮件需要使用的基本信息 *auth...

Rails 5 Test Prescriptions 第14章 Testing Exteranl Services(中断。)-程序员宅基地

文章浏览阅读68次。external testing strategy the service integration testintroduce VCRClient Unit Tests Why an Adapter?Testing for Error CasesSmoke Tests and VCR Options 冒烟测试!

MATLAB-MONTA离散元建模程序_matlab处理离散元问题-程序员宅基地

文章浏览阅读3.5k次。下载&nbsp;&gt;&nbsp; 信息化&nbsp;&gt;&nbsp; 其它&nbsp;&gt;&nbsp;基于蒙特卡罗法的二维随机裂隙模拟Matlab程序 ..._matlab处理离散元问题