Tuesday, May 24, 2016

Get Sharepoint List Items using SP Service


Below code copy and past into script Editor webpart and check

<script type="text/javascript" src="../SiteAssets/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../SiteAssets/jquery.SPServices-0.7.2.min.js"></scrip>

<script type="text/javascript">
//this is where the script starts after the page is loaded
$(document).ready(function() {

    GetSpeakers();

});

function GetSpeakers()
{
    //The Web Service method we are calling, to read list items we use 'GetListItems'
    var method = "GetListItems";
       
    //The display name of the list we are reading data from
    var list = "Employee";

    //We need to identify the fields we want to return. In this instance, we want the Name (Title),
    //Blog, and Picture fields from the Speakers list. You can see here that we are using the internal field names.
    //The display name field for the Speaker's name is "Name" and the internal name is "Title". You can see it can
    //quickly become confusing if your Display Names are completely differnt from your internal names.
    //For whatever list you want to read from, be sure to specify the fields you want returned.
    var fieldsToRead =     "<ViewFields>" +
                            "<FieldRef Name='Title' />" +
                            "<FieldRef Name='Name' />" +
                            "<FieldRef Name='Description' />" +
                            "<FieldRef Name='DOB' />" +
                            "<FieldRef Name='isActive' />" +
                        "</ViewFields>";
                           
    //this is that wonderful CAML query I was talking about earlier. This simple query returns
    //ALL rows by saying "give me all the rows where the ID field is not equal to 0". I then
    //tell the query to sort the rows by the Title field. FYI: a blank query ALSO returns
    //all rows, but I like to use the below query because it helps me know that I MEANT to
    //return all the rows and didn't just forget to write a query :)
    var query = "<Query>" +
                    "<Where>" +
                        "<Neq>" +
                            "<FieldRef Name='ID'/><Value Type='Number'>0</Value>" +
                        "</Neq>" +
                    "</Where>" +
                    "<OrderBy>" +
                        "<FieldRef Name='Title'/>" +
                    "</OrderBy>" +
                "</Query>";

    //Here is our SPServices Call where we pass in the variables that we set above
    $().SPServices({
        operation: method,
        async: false,  //if you set this to true, you may get faster performance, but your order may not be accurate.
        listName: list,
        CAMLViewFields: fieldsToRead,
        CAMLQuery: query,
        //this basically means "do the following code when the call is complete"
        completefunc: function (xData, Status) {
            //this code iterates through every row of data returned from the web service call
            $(xData.responseXML).SPFilterNode("z:row").each(function() {
                //here is where we are reading the field values and putting them in JavaScript variables
                //notice that when we read a field value there is an "ows_" in front of the internal field name.
                //this is a SharePoint Web Service quirk that you need to keep in mind.
                //so to read a field it is ALWAYS $(this).attr("ows_");
                           
                //get the title field (Speaker's Name)
                var Title = ($(this).attr("ows_Title"));
                           
                //get the blog url, SharePoint stores a url in the form of
                //We only want the . To accomplish this we use the javascript "split" function
                //which will turn into an array where the first element [0]
                //is the url.   Catch all that? if you didn't this is another reason you should be
                //a developer if you are writing JavaScript and jQuery :)
                var Name = ($(this).attr("ows_Name"));
                           
                //same thing as the blog, a picture is stored as
                var Description = ($(this).attr("ows_Description"));

                var DOB = ($(this).attr("ows_DOB"));

                var isActive = ($(this).attr("ows_isActive"));
                if(isActive)
                    isActive="Yes";
                else
                    isActive="No";
                
               // alert("Title: "+Title+"Name: "+Name+"Description:"+Description+"DOB:"+DOB+"is Active"+isActive);
                //call a function to add the data from the row to a table on the screen
                var liHtml = "
  • Name: " + Name +"
    Description: " + Description+"
    DOB: "+DOB+"
    Is active: "+isActive+"
  • "; 
                    $("#ulTasks").append(liHtml);
                               
                });               
            }
        });

    }

    // very simple function that adds a row to a table with the id of "speakerTable"
    // for every row of data returned from our SPServices call.
    // Each row of the table will display the picture of the speaker and
    // below the speaker's picture will be their name that is a hyperlink
    // to the speaker's blog.


    &lt/script>


    <ul id="ulTasks"/&gt




    Get SP List items using javascript object model

    Now we will go through how to get the List Items from SharePoint List using JavaScript Client Object model.


    One restriction in the JavaScript Client Object model is we can’t access the data from different site collections and it can run only in SharePoint environment.
    JavaScript Client Object model gives better performance to the Users since it makes only asynchronous calls to the Server side and retrieves data. It also loads only the requested data and not more that (ie. It retrieves only the Requested content from the server and it doesn’t load all the properties of the object)
    Below code snippet defines the retrieval of list items from SharePoint List using JavaScript model. (Check the inner comments for more details) 
    Below code past into Script Editor webpart and check 
    <script type="text/javascript"/>

    /*Below line will make sure your JavaScript method will be called only after the SP.js file loaded at the client side*/
    ExecuteOrDelayUntilScriptLoaded(QueryFollowUrl, "sp.js");

    function QueryFollowUrl()
    {
        //Gets the Client context of the Web
        var context = new SP.ClientContext.get_current();
        /*if your list exists in the subsite uncomment the below line and remove the above declaration*/
        //var context = new SP.ClientContext(‘/siteurl’);
        var web = context.get_web();

        //Change the List Name with yours
        this.list = web.get_lists().getByTitle('Employee');
           
        var query = SP.CamlQuery.createAllItemsQuery();
          
        listItems = this.list.getItems(query);

        context.load(list); 

        /*Now mention all the required filed internal name, since data from these fields only will be retrieved*/
        context.load(listItems, 'Include(Title,Name,Description,DOB,isActive)');
        //Makes asynchronous call to the Server, which will return the JSON objects
        context.executeQueryAsync(Function.createDelegate(this, this.successFollow), Function.createDelegate(this, this.failedFollow));
        return false;
    }

    //you can get the Error details if your Execution fails using get_message() method
    function failedFollow(sender, args)
    {
        var errorMsg = args.get_message();
    }
    /*Upon successful execution, Success delegate method will be called and all the requested objects will the loaded with contents*/
    function successFollow(sender, args)
    {
        var ListEnumerator = this.listItems.getEnumerator();

        while (ListEnumerator.moveNext())
        {
            var collection = ListEnumerator.get_current();

            /*Using get_item method you can pass the Field Internal name mentioned earlier and get the data in that respective column, if you try to use any other column other than we mentioned earlier, it will throw you error.*/

            var Title = collection.get_item('Title');
            var Name = collection.get_item('Name');
            var Description = collection.get_item('Description');
            var DOB = collection.get_item('DOB');
            var isActive = collection.get_item('isActive');
            //your code here
            var liHtml = "
  • Name: " + Name +"
    Description: " + Description+"
    DOB: "+DOB+"
    Is active: "+isActive+"
  • "; 
            $("#ulTasks").append(liHtml);

        }
    }

    </script&gt

    <!-- table where our speaker rows will go --&gt

    Friday, May 20, 2016

    Recursively walking through a directory tree and listing file names

     
     
    public partial class MainWindow : Window
    {
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            string sourcePath = @"C:\MasterPageArtifacts\";            
    
            static void DirSearch(string sourcePath)
            {
                try
                {
                    foreach (string d in Directory.GetDirectories(sourcePath))
                    {
                        foreach (string f in Directory.GetFiles(d))
                        {
                            listBox1.Items.Add(f);
                        }
                        DirSearch(d);
                    }
                }                      
                catch (Exception ex)
                {
                    listBox1.Items.Add(ex.Message);
                }
            }
        }
    }