Thursday 9 January 2014

Utilizing SPServices to Call SharePoint Search Web Service


SPServices from CodePlex provides a much simpler way to interact with SharePoint Search Web Service, as you can see from an example below. Please note that I've only requested documents from the query, if you want to return everything, remove ISDOCUMENT=true from the query.

 

<html dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta name="WebPartPageExpansion" content="full" />
<script language="javascript" src="jquery-1.8.2.min.js"></script>
<script language="javascript" src="jquery.SPServices-0.7.2.min.js"></script>
<script language="javascript">
    (function () {
        function querySearchService(scopeName, keywordToSearch, maxItemCount) {
            keywordToSearch = keywordToSearch.trim().replace(/\s+/g, "+");
            var queryText = "<QueryPacket xmlns='urn:Microsoft.Search.Query' Revision='1000'>"
            queryText += "<Query>"
            queryText += "<Range><StartAt>1</StartAt><Count>" + maxItemCount + "</Count></Range>"
            queryText += "<Context>"
            queryText += "<QueryText language='en-US' type='MSSQLFT'>"
            queryText += "SELECT Title, Path, IsDocument, ContentClass, Author, Rank, Size, Description, Write FROM scope() WHERE CONTAINS ('" + keywordToSearch + "') AND \"scope\"='" + scopeName + "' AND ISDOCUMENT=true ORDER BY Rank DESC"
            queryText += "</QueryText>"
// Keyword syntax
//   queryText += "<QueryText language='en-US' type='String'>" + keywordToSearch;
//   queryText += " Scope:" + scopeName;
//   queryText += "</QueryText>";

            queryText += "</Context>"
            queryText += "</Query>"
            queryText += "<EnableStemming>True</EnableStemming>"
            queryText += "<TrimDuplicates>True</TrimDuplicates>"
            queryText += "</QueryPacket>";
 
            alert(queryText);
 
            $().SPServices({
                operation: "Query",
                queryXml: queryText,
                completefunc: function (xData, Status) {
                    $(xData.responseXML).find("QueryResult").each(function () {
                        var array = new Array();
                        alert($(this).text());
                        var result = $.parseXML($(this).text());//$("<XmlResult>" + $(this).text() + "</XmlResult>");
                        var matches = result.find("Document");
                        if (matches.length == 0) {
                            alert("Nothing Found!");
                            return;
                        }
                        $("#dynamic-search-results").empty();
                        matches.each(function () {
                            url = $("Properties>Property:nth-child(2)>Value", $(this)).text();                        //$("Action>LinkUrl", $(this)).text();  
                            title = $("Properties>Property:nth-child(1)>Value", $(this)).text();
                            $("#resultDiv").append($("<p></p>").append($("<a></a>").prop("href", url).text(title)));
                        });
 
                    });
                }
 
            });
 
        }
 
        $(document).ready(function () {
            querySearchService("Entire Site", "SharePoint", 10);
 
        });
 
    })();
 
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled 2</title>
</head>
 
<body>
 <div id="resultDiv"></div>
</body>
 
</html>
 

Thursday 2 January 2014

Upload a File Using JavaScript by Calling _layouts/Upload.aspx Page


The technique is to build a new UI with file input element to interact with users while loading Upload.aspx within an hidden iframe. Once everything is ready, we swap our file input control with the one inside iframe, hence their ids have to be identical. This is due to the fact that the value of the file input element cannot be populated through javascript.
 
Please reference the source code below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">

<%@ Page Language="C#" %>
<html dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta name="WebPartPageExpansion" content="full" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.2.min.js"></script>

<script type="text/javascript">
       $(document).ready(function(){
              var iframe, fileInput, btnUpload;

              $("#myUpload").click(function(event){
                     //Hide the button and show animation
                     $(event.target).hide();
                     $("#imgLoading").show();
                    
                     //Set call back method
                     $(iframe).get(0).contentWindow.frameElement.commitPopup = function(){
                           window.location.reload();
                     };

                     //Swap file box with the one within iframe and then trigger the upload           

                     var oFile = $("input[name*='InputFile'][type='file']").detach();
                     var parentElement = $(fileInput).parent();
                     var iFile = $(fileInput).detach();

                     $(parentElement).append(oFile);
                     $(btnUpload).trigger("click");

              });

                                                      

              $("#uploadIframe").one("load", function(event){
                                                              iframe = event.target;

                                                              //Locate elements within iframe
                                                              fileInput = $("input[name*='InputFile'][type='file']", $(iframe).contents());
                                                              btnUpload = $("input[name*='btnOK']", $(iframe).contents());

                                                              //$("input[name*='InputFile'][type='file']", $(iframe).contents()).css("background-color", "red").val("hello");
                                                             
                                                       });
                           
       });

</script>
<title>Untitled 1</title>
</head>
<body>
 
<p>
<input name="ctl00$PlaceHolderMain$ctl01$ctl05$InputFile" class="ms-fileinput" id="ctl00_PlaceHolderMain_ctl01_ctl05_InputFile" onfocus="ResetSpFormOnSubmitCalled();" type="file" size="35" Validators="[object HTMLSpanElement],[object HTMLSpanElement]"/>
<button id="myUpload">Upload</button>
<img id="imgLoading" src="/_layouts/images/gears_anv4.gif" border="0px;" style="display:none;" />
</p>
<p>
<iframe id="uploadIframe" src="https://Some-Site/_layouts/Upload.aspx?List={A2176B62-CF75-4A24-AB95-5491F2D6F28E}&RootFolder=&IsDlg=0" style="width:0px;height:0px;border-width:0px;">
</iframe>
</p>
</body>
</html>