About Me

My photo
a Dynamic and Energetic guy.....
Showing posts with label CSOM. Show all posts
Showing posts with label CSOM. Show all posts

Tuesday, January 31, 2017

Retrieving SPList Data From SharePoint Online Site using CSOM

using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SPOnlineDataAccess
{
    public partial class Form1 : System.Windows.Forms.Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void LoadDefaultValues()
        {
            txtSiteUrl.Text = "https://abc.sharepoint.com/sites/testsite";
            txtListName.Text = "OnlineList";
            txtUserEmail.Text = "user1@xyz.com";
            txtPassword.Text = "pass@123qaz";
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            DataTable dtResults = ReadSPList();
            dataGridView1.DataSource = dtResults;
        }


        private DataTable ReadSPList()
        {
            using (ClientContext clientContext = GetContextObject())
            {
                try
                {
                    DataTable dtListData = new DataTable();
                    //Creating DataTable Columns
                    dtListData.Columns.Add("Title", typeof(String));
                    dtListData.Columns.Add("Designation", typeof(String));
                    dtListData.Columns.Add("EmpID", typeof(String));

                    //Getting Data From SharePoint
                    Web web = clientContext.Web;
                    clientContext.Load(web, website => website.ServerRelativeUrl);
                    clientContext.ExecuteQuery();                  

                    //Read SPList called "OnlineList"
                    List myList = web.Lists.GetByTitle(txtListName.Text);

                    // This creates a CamlQuery that has a RowLimit of 1000, and also specifies Scope="RecursiveAll"
                    // so that it grabs all list items, regardless of the folder they are in.
                    CamlQuery query = CamlQuery.CreateAllItemsQuery(1000);
                    ListItemCollection items = myList.GetItems(query);

                    // Retrieve all items in the ListItemCollection from List.GetItems(Query).
                    clientContext.Load(items);
                    clientContext.ExecuteQuery();

                    for (int count = 0; count < items.Count; count++)
                    {
                        DataRow dr = dtListData.NewRow();
                        dr["Title"] = items[count]["Title"].ToString();
                        dr["Designation"] = items[count]["Designation"].ToString();
                        dr["EmpID"] = items[count]["EmpID"].ToString();

                        dtListData.Rows.Add(dr);
                    }
                    return dtListData;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return null;
                }
            }
        }

        private ClientContext GetContextObject()
        {
            string siteUrl = txtSiteUrl.Text;
            string userName = txtUserEmail.Text;
            string password = txtPassword.Text;
            SecureString _password = GetPasswordFromInput(password);

            ClientContext context = new ClientContext(siteUrl);
            context.Credentials = new SharePointOnlineCredentials(userName, _password);
            return context;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadDefaultValues();
        }

        private SecureString GetPasswordFromInput(string password)
        {
            //Get the user's password as a SecureString
            SecureString securePassword = new SecureString();
            char[] arrPassword = password.ToCharArray();
            foreach (char c in arrPassword)
            {
                securePassword.AppendChar(c);
            }

            return securePassword;
        }

    }
}


Wednesday, December 16, 2015

Content Editor WebPart With CSOM

Im writing simple code to save data to LIST using CSOM, include in CEWP.
The Code of full file that can be bounded to CEWP.

=======================================================================

<div onkeydown='javascript:if (event.keyCode == 13) postSurvey()'>
    <p>1. How is the weather?<br />
         <input name='q1' id='q1Bad' type='radio' value='Bad'/><label for='q1Bad'> Bad</label><br />
         <input name='q1' id='q1Good' type='radio' value='Good'/><label for='q1Good'> Good</label><br />
         <input name='q1' id='q1Great' type='radio' value='Great'/><label for='q1Great'> Great</label>
    </p>
    <p>2. How are you doing?<br />
         <input name='q2' id='q2Fine' type='radio' value='Fine'/> <label for='q2Fine'>Fine</label><br />
         <input name='q2' id='q2Good' type='radio' value='Good' /><label for='q2Good'> Good</label><br />
         <input name='q2' id='q2Great' type='radio' value='Great' /><label for='q2Great'> Great</label>
    </p>
    <input type='button' value='Submit' onclick='javascript:postSurvey();' />

</div>

/*
These 2 files are really important, The Order is also important
*/

<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js" ></script>

<script language='javascript' type='text/javascript'>
        function getCheckedValue(buttonGroup) {
            if (!buttonGroup)
                return '';
            var objLength = buttonGroup.length;
            if (objLength == undefined) {
                if (buttonGroup.checked)
                    return buttonGroup.value;
                else
                     return '';
            }
            for (var i = 0; i < objLength; i++) {
                if (buttonGroup[i].checked)
                    return buttonGroup[i].value;
            }
            return '';
        }
     
        function postSurvey() {
       
            // Retrieve the radio button values

            var question1 = getCheckedValue(document.getElementsByName('q1'));
            var question2 = getCheckedValue(document.getElementsByName('q2'));

            /* Validate the response.
               Do nothing more until all questions are answered.
            */
            if (question1 == '' || question2 == '') {
                alert('Please answer all questions.')
                return;
            }

// Get the current context
           var context = new SP.ClientContext.get_current();

           // Get the current site (SPWeb)
           var web = context.get_web();

           // Get the survey list
           var list = web.get_lists().getByTitle('SampleSurvey');

           // Create a new list item
           var itemCreateInfo = new SP.ListItemCreationInformation();
           var listItem = list.addItem(itemCreateInfo);

           /* Set fields in the item.
              In managed code, this would be listItem[fieldname] = value.
              In Javascript, call listItem.set_item(fieldName,value).
           */
           listItem.set_item('How_x0020_is_x0020_the_x0020_wea', question1);
           listItem.set_item('How_x0020_are_x0020_you_x0020_do', question2);
           listItem.update();

           // Create callback handlers
           var success = Function.createDelegate(this, this.onSuccess);
           var failure = Function.createDelegate(this, this.onFailure);

           // Execute an async query
           context.executeQueryAsync(success,failure);

        }

// Async query succeeded.
function onSuccess(sender, args) {

    alert('Thank you for responding to our survey!');
     
    // Refresh the page.
    SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
}

// Async query failed.
function onFailure(sender, args) {
    alert(args.get_message());
}
    </script>

My Masters