понедельник, 18 июля 2011 г.

Sharepoint WCF and java script

Сегодня поговорим о возможности запросов к пользовательским wcf из java script кода.
Как создавать пользовательский  wcf я не буду рассматривать, это очень просто. Рассмотрим мой js класс для работы с wcf.
var MakeClass = function(){
    return function( args ){
        if( this instanceof arguments.callee ){
            if( typeof this.__construct == "function" ) this.__construct.apply( this, args );
        }else return new arguments.callee( arguments );
    };
}
var NewClass = function( variables, constructor, functions ){
    var retn = MakeClass();
    for( var key in variables ){
        retn.prototype[key] = variables[key];
    }
    for( var key in functions ){
        retn.prototype[key] = functions[key];
    }
    retn.prototype.__construct = constructor;
    return retn;
}
var GetCurrantUser = NewClass({
 "UserLogin":"",
 "UserName":"",
 "web":null,
 "currentUser":null,
 "context":null,
 "propertyName":"Title",
 "url":"",
 "params":null,
 "method":""
 },
 function(url,params,method)
 {
    this.method = method;
    this.params = params;
    this.url = 'http://'+document.domain+url;
    this.connect();
 },
 {
 "connect": function()
 {
                        try
                            {
                            this.context = new SP.ClientContext.get_current();
                            this.web = this.context.get_web();
                            this.currentUser = this.web.get_currentUser();
                            this.currentUser.retrieve();
                            this.context.load(this.web);
                            this.context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod), Function.createDelegate(this, this.onFailureMethod));
                            }
                            catch(e)
                            {
                            var self = this;
                            setTimeout(function() {self.connect();}, 5000);
                            }
 },
 "onSuccessMethod":function(sender, args)
 {
 var userObject = this.web.get_currentUser();
 this.Set_userData(userObject.get_title(),userObject.get_loginName());
    //alert('User name:' + userObject.get_title() + '\n Login Name:' + userObject.get_loginName());
 },
 "onFailureMethod":function(sender, args)
 {
 //alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
 alert('Error');
 },
 "Set_userData":function(name,login)
 {
    this.UserName = name;
    this.UserLogin = login;
    this.GetUserPropertyByAccountName();
 },
 "get_hostname_from_url":function(url) {
    return url.match(/:\/\/(.[^\/]+)/)[1];
},
 "GetUserPropertyByAccountName": function() {
 // VariablesW
 var xmlHttpReq = null;
 // Mozilla/Safari
 if (window.XMLHttpRequest) {
  xmlHttpReq = new XMLHttpRequest();
 }
 //IE
 else if (window.ActiveXObject) {
  xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
 }
 if (xmlHttpReq) {
     xmlHttpReq.open('POST', this.url, false); //если мы ставим тут true то это значит асинхронность запроса, и нужно писать метод для него, он у нас был =) но там был неверный хмл
  //Set the Headers
  xmlHttpReq.setRequestHeader('Content-Type', 'text/xml');
  xmlHttpReq.setRequestHeader('SOAPAction', 'http://tempuri.org/I'+this.url.split("/")[this.url.split("/").length-1].match(/.*(?=[.])/)+'/'+this.method);
  //get the XML Request string
    var xml_params="";
      for(var key in this.params ){
      xml_params+='<'+key+'>'+this.params[key]+'</'+key+'>';
    }
  xmlHttpReq.send('<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">'
    + '<s:Body>'
    + '<'+this.method+' xmlns="http://tempuri.org/">'
    + xml_params
    + '</'+this.method+'>'
    + ' </s:Body>'
    + '</s:Envelope>');
if (xmlHttpReq.readyState == 4) {
    if (xmlHttpReq.status == 200) {
    var re = new RegExp("(?:(<"+this.method+"Result>))(.*(?=(<\/"+this.method+"Result>)))", "g");
    alert(xmlHttpReq.responseText.match(re));
    alert(xmlHttpReq.responseText);
    }
    else {
     alert(xmlHttpReq);
    }
   }
 }
 else {
  alert('unable to create XMLHttpRequest object');
 }
}
})
var user = GetCurrantUser('/_vti_bin/WCF/WCFjs.svc',{"str":"str"},"HelloWorld");
Для работы с wcf вам просто нужно в конструктор передать путь к нему ('/_vti_bin/WCF/WCFjs.svc'), название и значение параметров ({"str":"str"}) и им метода ("HelloWorld").
Результатом будет вывод на экран ответа от сервера, дальнейший разбор xml зависит от ваших задач. Спасибо.