Search This Blog

Friday, September 9, 2016

CRUD On List Items Using Web Services and jQuery In SharePoint 2013

Now, I will demo all the operations on list items including retrieve, create, update and delete onlist items.

Retrieve the list items:

  1. function retriveListItem()  
  2. {  
  3.     var soapEnv = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \  
  4. <soapenv:Body> \  
  5. <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \  
  6. <listName>companyInfo</listName> \  
  7. <viewFields> \  
  8. <ViewFields> \  
  9. <FieldRef Name='Company' /> \  
  10. <FieldRef Name='Industry' /> \  
  11. </ViewFields> \  
  12. </viewFields> \  
  13. </GetListItems> \  
  14. </soapenv:Body> \  
  15. </soapenv:Envelope>";  
  16.     $.ajax(  
  17.     {  
  18.         url: _spPageContextInfo.webAbsoluteUrl + "/apps/_vti_bin/Lists.asmx",  
  19.         type: "POST",  
  20.         dataType: "xml",  
  21.         data: soapEnv,  
  22.         complete: processResult,  
  23.         contentType: "text/xml; charset=\"utf-8\""  
  24.     });  
  25. }  
  26.   
  27. function processResult(xData, status)  
  28. {  
  29.     var MainResult = "";  
  30.     $(xData.responseXML).find("z\\:row").each(function()  
  31.     {  
  32.         var companyName = $(this).attr("ows_Company");  
  33.         var Industry = $(this).attr("ows_Industry");  
  34.         MainResult += MainResult + companyName + "-" + Industry + "\n";  
  35.     });  
  36.     $('#ResultDiv').text(MainResult);  
  37. }  
Create list item:
Here is the main code in detail:

  1. function createListItem() {  
  2.     var batch =  
  3.         "<Batch OnError=\"Continue\"> \  
  4.     <Method ID=\"1\" Cmd=\"New\"> \  
  5.         <Field Name=\"Company\">" + $("#Company").val() + "</Field> \  
  6.          <Field Name=\"Industry\">" + $("#Industry").val() + "</Field> \  
  7.               </Method> \  
  8. ch>";  
  9.   
  10.     var soapEnv =  
  11.         "<?xml version=\"1.0\" encoding=\"utf-8\"?> \  
  12. <soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \  
  13.     xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" \  
  14.     xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> \  
  15.   <soap:Body> \  
  16.     <UpdateListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\"> \  
  17.       <listName>companyInfo</listName> \  
  18.       <updates> \  
  19.         " + batch + "</updates> \  
  20.     </UpdateListItems> \  
  21.   </soap:Body> \  
  22. </soap:Envelope>";  
  23.   
  24.     $.ajax({  
  25.         url: _spPageContextInfo.webAbsoluteUrl+ "/apps/_vti_bin/Lists.asmx",  
  26.         beforeSend: function(xhr) {  
  27.             xhr.setRequestHeader("SOAPAction",  
  28.             "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");  
  29.         },  
  30.         type: "POST",  
  31.         dataType: "xml",  
  32.         data: soapEnv,  
  33.         complete: processResult,  
  34.         contentType: "text/xml; charset=utf-8"  
  35.     });  
  36. }  
  37.   
  38. function processResult(xData, status) {  
  39.     retriveListItem();  
  40. }  

Update list item:
Here is the main code in detail:
  1. function updateListItem() {  
  2.       
  3.     var UpdateNewItemXml =  
  4.         "<Batch OnError=\"Continue\"> \  
  5.     <Method ID=\"1\" Cmd=\"Update\"> \  
  6.         <Field Name=\"ID\">7</Field>\  
  7.          <Field Name=\"Industry\">" + $("#Industry").val() + "</Field> \  
  8.               </Method> \</Batch>";  
  9.    var soapEnv =  
  10.         "<?xml version=\"1.0\" encoding=\"utf-8\"?> \  
  11. <soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \  
  12.     xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" \  
  13.     xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> \  
  14.   <soap:Body> \  
  15.     <UpdateListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\"> \  
  16.       <listName>companyInfo</listName> \  
  17.       <updates> \  
  18.         " + UpdateNewItemXml + "</updates> \  
  19.     </UpdateListItems> \  
  20.   </soap:Body> \  
  21. </soap:Envelope>";  
  22.   
  23.     $.ajax({  
  24.         url: _spPageContextInfo.webAbsoluteUrl + "/apps/_vti_bin/Lists.asmx",  
  25.         beforeSend: function (xhr) {  
  26.             xhr.setRequestHeader("SOAPAction",  
  27.             "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");  
  28.         },  
  29.         type: "POST",  
  30.         dataType: "xml",  
  31.         data: soapEnv,  
  32.         complete: processResult,  
  33.         contentType: "text/xml; charset=utf-8"  
  34.     });  
  35. }  
  36. function processResult(xData, status) {  
  37.     retriveListItem();  
}

Delete list item:
here is the main code in detail:
  1. function deleteListItem()  
  2. {  
  3.     var DeleteItemXml = "<Batch OnError=\"Continue\"> \  
  4.             <Method ID=\"1\" Cmd=\"Delete\"> \  
  5.                 <Field Name=\"ID\">7</Field>\  
  6.                 <Field Name=\"Company\">" + $("#Company").val() + "</Field> \  
  7.                       </Method> \</Batch>";  
  8.     var soapEnv = "<?xml version=\"1.0\" encoding=\"utf-8\"?> \  
  9.         <soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \  
  10.             xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" \  
  11.             xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> \  
  12.           <soap:Body> \  
  13.             <UpdateListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\"> \  
  14.               <listName>companyInfo</listName> \  
  15.               <updates> \  
  16.                 " + DeleteItemXml + "</updates> \  
  17.             </UpdateListItems> \  
  18.           </soap:Body> \  
  19.         </soap:Envelope>";  
  20.     $.ajax(  
  21.     {  
  22.         url: _spPageContextInfo.webAbsoluteUrl + "/apps/_vti_bin/Lists.asmx",  
  23.         beforeSend: function(xhr)  
  24.         {  
  25.             xhr.setRequestHeader("SOAPAction""http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");  
  26.         },  
  27.         type: "POST",  
  28.         dataType: "xml",  
  29.         data: soapEnv,  
  30.         complete: processResult,  
  31.         contentType: "text/xml; charset=utf-8"  
  32.     });  
  33. }  
  34.   
  35. function processResult(xData, status)  
  36. {  
  37.     retriveListItem();  
}

Sunday, September 4, 2016

Execute PowerShell Script from C#

Option 1

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @"powershell.exe";
startInfo.Arguments = @"& 'c:\Scripts\test.ps1'";
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();

string output = process.StandardOutput.ReadToEnd();
Assert.IsTrue(output.Contains("StringToBeVerifiedInAUnitTest"));


string errors = process.StandardError.ReadToEnd();
Assert.IsTrue(string.IsNullOrEmpty(errors));

With the contents of the script being:
$someVariable = "StringToBeVerifiedInAUnitTest"
$someVariable


Option 2

C:\Foo1.PS1 Hello World Hunger C:\Foo2.PS1 Hello World


scriptFile = "C:\Foo1.PS1"


parameters = "parm1 parm2 parm3" ... variable length of params

private static void RunPowershellScript(string scriptFile, string scriptParameters)
{
    RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
    Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
    runspace.Open();
    RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
    Pipeline pipeline = runspace.CreatePipeline();
    Command scriptCommand = new Command(scriptFile);
    Collection<CommandParameter> commandParameters = new Collection<CommandParameter>();
    foreach (string scriptParameter in scriptParameters.Split(' '))
    {
        CommandParameter commandParm = new CommandParameter(null, scriptParameter);
        commandParameters.Add(commandParm);
        scriptCommand.Parameters.Add(commandParm);
    }
    pipeline.Commands.Add(scriptCommand);
    Collection<PSObject> psObjects;
    psObjects = pipeline.Invoke();
}

Option 3


string cmdArg = ".\script.ps1 -foo bar"            Collection<PSObject> psresults;
using (Pipeline pipeline = _runspace.CreatePipeline())
            {
                pipeline.Commands.AddScript(cmdArg);
                pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
                psresults = pipeline.Invoke();
            }
return psresults;


Option 4


Here is a way to add Paramaters to the script if you used pipeline.Commands.AddScript(Script);

 This is with using an HashMap as paramaters the key being the name of the variable in the script and the value is the value of the variable.

 pipeline.Commands.AddScript(script));


 FillVariables(pipeline, scriptParameter);


 Collection<PSObject> results = pipeline.Invoke();

And the fill variable method is:

private static void FillVariables(Pipeline pipeline, Hashtable scriptParameters)
{
    // Add additional variables to PowerShell
    if (scriptParameters != null)
    {
        foreach (DictionaryEntry entry in scriptParameters)
        {
            CommandParameter Param = new CommandParameter(entry.Key as String, entry.Value);
            pipeline.Commands[0].Parameters.Add(Param);
        }
    }
}

this way you can easily add multiple parameters to a script. Ive also noticed that if you want to get a value from a variable in you script like so:

Object resultcollection = runspace.SessionStateProxy.GetVariable("results");


Others URL:
http://olivier-richard.azurewebsites.net/call-a-powershell-script-from-c-code/
http://www.c-sharpcorner.com/forums/powershell-script-run-from-c-sharp-app
http://en.community.dell.com/techcenter/systems-management/w/wiki/3479.executing-microsoft-powershell-scripts-that-use-the-vmware-powercli-snap-in-via-c-and-microsoft-net
http://jeffmurr.com/blog/?p=142




Friday, September 2, 2016

Upload documents In SharePoint List/Library Using Rest API

<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
<script type="text/javascript">
$(document).ready(function()
{
// Check for FileReader API (HTML5) support.
    if (!window.FileReader) {
        alert('This browser does not support the FileReader API.');
    }
 
});
 
// Upload the file.
// You can upload files up to 2 GB with the REST API.
function uploadFile() {
 
    // Define the folder path for this example.
    var serverRelativeUrlToFolder = '/TestDocLib';
 
    // Get test values from the file input and text input page controls.
    var fileInput = jQuery('#getFile');
    var newName = jQuery('#displayName').val();
     var txtdesc= jQuery('#txtdesc').val();
 
    // Get the server URL.
    var serverUrl = _spPageContextInfo.webAbsoluteUrl;
 
    // Initiate method calls using jQuery promises.
    // Get the local file as an array buffer.
    var getFile = getFileBuffer();
    getFile.done(function (arrayBuffer) {
 
        // Add the file to the SharePoint folder.
        var addFile = addFileToFolder(arrayBuffer);
        addFile.done(function (file, status, xhr) {
 
            // Get the list item that corresponds to the uploaded file.
            var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
            getItem.done(function (listItem, status, xhr) {
 
                // Change the display name and title of the list item.
                var changeItem = updateListItem(listItem.d.__metadata);
                changeItem.done(function (data, status, xhr) {
                    alert('file uploaded and updated');
                });
                changeItem.fail(onError);
            });
            getItem.fail(onError);
        });
        addFile.fail(onError);
    });
    getFile.fail(onError);
 
    // Get the local file as an array buffer.
    function getFileBuffer() {
        var deferred = jQuery.Deferred();
        var reader = new FileReader();
        reader.onloadend = function (e) {
            deferred.resolve(e.target.result);
        }
        reader.onerror = function (e) {
            deferred.reject(e.target.error);
        }
        reader.readAsArrayBuffer(fileInput[0].files[0]);
        return deferred.promise();
    }
 
    // Add the file to the file collection in the Shared Documents folder.
    function addFileToFolder(arrayBuffer) {
 
        // Get the file name from the file input control on the page.
        var parts = fileInput[0].value.split('\\');
        var fileName = parts[parts.length - 1];
 
        // Construct the endpoint.
        var fileCollectionEndpoint = String.format(
                "{0}/_api/web/getfolderbyserverrelativeurl('{1}')/files" +
                "/add(overwrite=true, url='{2}')",
                serverUrl, serverRelativeUrlToFolder, fileName);
 
        // Send the request and return the response.
        // This call returns the SharePoint file.
        return jQuery.ajax({
            url: fileCollectionEndpoint,
            type: "POST",
            data: arrayBuffer,
            processData: false,
            headers: {
                "accept": "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "content-length": arrayBuffer.byteLength
            }
        });
    }
 
    // Get the list item that corresponds to the file by calling the file's ListItemAllFields property.
    function getListItem(fileListItemUri) {
 
        // Send the request and return the response.
        return jQuery.ajax({
            url: fileListItemUri,
            type: "GET",
            headers: { "accept": "application/json;odata=verbose" }
        });
    }
 
    // Change the display name and title of the list item.
    function updateListItem(itemMetadata) {
 
        // Define the list item changes. Use the FileLeafRef property to change the display name.
        // For simplicity, also use the name as the title.
        // The example gets the list item type from the item's metadata, but you can also get it from the
        // ListItemEntityTypeFullName property of the list.
        var body = String.format("{{'__metadata':{{'type':'{0}'}},'FileLeafRef':'{1}','Title':'{2}'}}",
            itemMetadata.type, newName,txtdesc);
 
        // Send the request and return the promise.
        // This call does not return response content from the server.
        return jQuery.ajax({
            url: itemMetadata.uri,
            type: "POST",
            data: body,
            headers: {
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "content-type": "application/json;odata=verbose",
                "content-length": body.length,
                "IF-MATCH": itemMetadata.etag,
                "X-HTTP-Method": "MERGE"
            }
        });
    }
}
 
// Display error messages.
function onError(error) {
    alert(error.responseText);
}</script>
<input id="getFile" type="file"/><br />
<input id="displayName" type="text"/><br />
<input id="txtdesc" type="text"  /><br />
<input id="addFileButton" type="button" value="Upload" onclick="uploadFile()"/>
</asp:Content>