Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Saturday, October 03, 2015

CRUD OPERATIONS USING SILVERLIGHT CLIENT OBJECT MODEL

XAML:-
<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" x:Class="SilverlightProject1.MainPage"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="Green" Width="605" Height="300" Margin="0,0,-205,0" VerticalAlignment="Stretch">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="0*"/>
            <ColumnDefinition Width="14*"/>
            <ColumnDefinition Width="168*"/>
            <ColumnDefinition Width="423*"/>
            <ColumnDefinition Width="0*"/>
            <ColumnDefinition Width="0*"/>
        </Grid.ColumnDefinitions>

        <sdk:Label HorizontalAlignment="Left" Height="28" VerticalAlignment="Top" Width="120" Margin="24,74,0,0" Content="Enter Username&#x9;" Grid.Column="2"/>
        <TextBox HorizontalAlignment="Left" Height="20" TextWrapping="Wrap" VerticalAlignment="Top" Width="130" Margin="118,70,0,0" RenderTransformOrigin="0.5,0.5" Name="txtTitle" Grid.Column="2" Grid.ColumnSpan="2" Text="{Binding Path=Title, Mode=OneTime}"  />
        <sdk:Label HorizontalAlignment="Left" Height="28" VerticalAlignment="Top" Width="120" Margin="22,103,0,0" Content="Enter Password" Grid.Column="2"/>
        <TextBox HorizontalAlignment="Left" Height="20" TextWrapping="Wrap" VerticalAlignment="Top" Width="129" Margin="119,103,0,0" RenderTransformOrigin="0.5,0.5" Name="txtPassword" Grid.Column="2" Grid.ColumnSpan="2" Text="{Binding Path=Password, Mode=OneTime}"  />
        <Button Content="Save" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="25,150,0,0" Click="btnSave_Click" Name="btnSave" Grid.Column="2" Height="22"/>
        <Button Content="Search" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="109,151,0,0" Name="btnSearch" Click="btnSearch_Click" Grid.Column="2" Grid.ColumnSpan="2" Height="22" />
        <Button Content="Update" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="26,151,0,0" Name="btnUpdate" Click="btnUpdate_Click" Grid.Column="3" Height="22" />
        <Button Content="Delete" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="109,151,0,0" Name="btnDelete" Click="btnDelete_Click" Grid.Column="3" Height="22" />
        <sdk:DataGrid HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="440" Margin="2,191,0,0" Name="dgLogin" GridLinesVisibility="All" Grid.ColumnSpan="4"/>
        <sdk:Label HorizontalAlignment="Left" Height="28" VerticalAlignment="Top" Width="100" Margin="109,20,0,0" Content="" Name="lblID" Grid.Column="2" Grid.ColumnSpan="2"/>
        <ComboBox Height="37" HorizontalAlignment="Left" Margin="118,20,0,0" Name="ddlBindData" VerticalAlignment="Top" Width="247" DisplayMemberPath="Title" SelectedValuePath="ID" SelectedValue="{Binding Path=ID, Mode=TwoWay}" Grid.ColumnSpan="2" Grid.Column="2"  />
        <sdk:Label HorizontalAlignment="Left" Height="28" VerticalAlignment="Top" Width="120" Margin="0,25,0,0" Content="Select Username" Grid.Column="2"/>
    </Grid>
</UserControl>
 
CS File:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.SharePoint.Client;

namespace SilverlightProject1
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            loadListsData();
            getData();
        }

        private ClientContext context = null;
        private Web web = null;
        //private IEnumerable<List> lists = null;
        private List selectedList = null;
        private IEnumerable<ListItem> listItems = null;
        private IEnumerable<ListItem> SearchListItem = null;
        private delegate void UpdateUI();
        //string strTitle, strPassword = "";
        public class LItem
        {
            public int ID { get; set; }
            public string Title { get; set; }
            public string Status { get; set; }
            //public string Priority { get; set; }
        }

        public class LoginSearch
        {
            public string strTitle  { get; set; }
            public string strPassword { get; set; }
        }

        public class Login
        {
            public int ID { get; set; }
            public string Title { get; set; }
        }

        public void getData()
        {
            try
            {
                ClientContext context = ClientContext.Current;
                Web objWeb = context.Web;
                List lstNewThoughts = objWeb.Lists.GetByTitle("Login");
                CamlQuery strQuery = new CamlQuery();
                strQuery.ViewXml = "<View><Query><OrderBy><FieldRef Name='Title' /></OrderBy></Query></View>";
                var items = lstNewThoughts.GetItems(strQuery);
                context.Load(lstNewThoughts);
                myLoginColl = context.LoadQuery(items.Include(l => l["Title"], l => l.Id));
                context.ExecuteQueryAsync(OnListItems1LoadSucceeded, OnFailure1);
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.ToString());
            }
        }
        private delegate void UpdateUIMethod1();
        private void OnListItems1LoadSucceeded(object sender, ClientRequestSucceededEventArgs e)
        {
            UpdateUIMethod1 updateUI = LoadListItems1;
            this.Dispatcher.BeginInvoke(updateUI);
        }
        private void OnFailure1(object sender, ClientRequestFailedEventArgs e)
        {
            MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
        }
        private void LoadListItems1()
        {
            ddlBindData.Visibility = System.Windows.Visibility.Visible;
            List<Login> lItems = new List<Login>();
            foreach (ListItem item in myLoginColl.ToList())
                lItems.Add(new Login
                {
                    Title = item["Title"].ToString(),
                    ID = item.Id,
                });
            ddlBindData.ItemsSource = lItems;
        }
        public void loadListsData()
        {
            context = ClientContext.Current;
            web = context.Web;
            selectedList = web.Lists.GetByTitle("Tasks");
            CamlQuery query = new CamlQuery();
            query.ViewXml = "<View><RowLimit>10</RowLimit></View>";
            var items = selectedList.GetItems(query);
            context.Load(selectedList);
            listItems = context.LoadQuery(items.Include(l => l["Title"], l => l["Status"], l => l.Id));
            context.ExecuteQueryAsync(OnListItemsLoadSucceeded, OnFailure1);

        }
        private void OnSearchLoadSucceeded(object sender, ClientRequestSucceededEventArgs e)
        {
            //MessageBox.Show(ddlBindData.SelectedValue.ToString());

            UpdateUI updateUI = LoadSearchListItems;
            this.Dispatcher.BeginInvoke(updateUI);
            foreach (ListItem item1 in SearchListItem.ToList())
            {
                txtTitle.Text = item1["Title"].ToString();
                txtPassword.Text = item1["Password"].ToString();
                break;
            }
        }

        private void LoadSearchListItems()
        {
            List<LoginSearch> lItems = new List<LoginSearch>();
            foreach (ListItem item1 in SearchListItem.ToList())
            {
                lItems.Add(new LoginSearch
                {
                    strTitle = item1["Title"].ToString(),
                    strPassword = item1["Password"].ToString(),
                });
                txtTitle.Text = item1["Title"].ToString();
                txtPassword.Text = item1["Password"].ToString();
                break;
            }
        }
       
        /*private void LoadSearchListItems()
        {
            List<LoginSearch> lItems = new List<LoginSearch>();
            foreach (ListItem item1 in SearchListItem.ToList())
            {
                lItems.Add(new LoginSearch
                {
                    strTitle = item1["Title"].ToString(),
                    strPassword = item1["Password"].ToString(),
                });
                txtTitle.Text = item1["Title"].ToString();
                txtPassword.Text = item1["Password"].ToString();
                break;
            }
           
        }*/

        private void OnListItemsLoadSucceeded(object sender, ClientRequestSucceededEventArgs e)
        {
            UpdateUI updateUI = LoadListItems;
            this.Dispatcher.BeginInvoke(updateUI);
        }
        private void OnFailure(object sender, ClientRequestFailedEventArgs e)
        {
            MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
        }
        private void LoadListItems()
        {
            dgLogin.Visibility = System.Windows.Visibility.Visible;
            List<LItem> lItems = new List<LItem>();
            foreach (ListItem item in listItems.ToList())
                lItems.Add(new LItem
                {
                    Title = item["Title"].ToString(),
                    ID = item.Id,
                    Status = item["Status"].ToString()
                });
            dgLogin.ItemsSource = lItems;
        }


        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ClientContext context = ClientContext.Current;
                Web currentWeb = context.Web;
                List lst = currentWeb.Lists.GetByTitle("Login");
                ListItem item = lst.AddItem(new ListItemCreationInformation());
                item["Title"] = txtTitle.Text;
                item["Password"] = txtPassword.Text;
                item.Update();
                context.Load(lst, LoginList => LoginList.Title);
                context.ExecuteQueryAsync(onQuerySucceeded, onQueryFailed);
            }
            catch (Exception Ex)
            {

                MessageBox.Show(Ex.ToString());
            }
        }

        private void onQuerySucceeded(object sender, ClientRequestSucceededEventArgs args)
        {
            UpdateUIMethod updateUI = DisplayInfo;
            this.Dispatcher.BeginInvoke(updateUI);
            getData();
        }

        private void DisplayInfo()
        {
            MessageBox.Show("Item Inserted Successfully");
            txtTitle.Text = "";
            txtPassword.Text = "";
            txtTitle.Focus();
        }

        private delegate void UpdateUIMethod();

        private void onQueryFailed(object sender, ClientRequestFailedEventArgs args)
        {
            MessageBox.Show("Request failed. " + args.Message + "\n" + args.StackTrace);
        }

        private IEnumerable<ListItem> myColl = null;
        private IEnumerable<ListItem> myLoginColl = null;
        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ClientContext context = ClientContext.Current;
                Web objWeb = context.Web;
                List lstNewThoughts = objWeb.Lists.GetByTitle("Login");
                CamlQuery strQuery = new CamlQuery();
                strQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>"+ddlBindData.SelectedValue.ToString()+"</Value></Eq></Where></Query></View>";
                var items = lstNewThoughts.GetItems(strQuery);
                context.Load(lstNewThoughts);
                SearchListItem = context.LoadQuery(items.Include(l => l["Title"], l => l["Password"], l=>l.Id ));
                context.ExecuteQueryAsync(OnSearchLoadSucceeded, OnFailure);
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.ToString());
            }
        }

        private void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int itemID = int.Parse(ddlBindData.SelectedValue.ToString());
                ClientContext context = ClientContext.Current;
                Web objWeb = context.Web;
                List oList = objWeb.Lists.GetByTitle("Login");
                ListItem oListItem = oList.GetItemById(itemID);
                oListItem["Title"] = txtTitle.Text;
                oListItem["Password"] = txtPassword.Text;
                oListItem.Update();
                context.ExecuteQueryAsync(onQueryUpdateSucceeded, onQueryUpdateFailed);

            }
            catch (Exception Ex)
            {

                MessageBox.Show(Ex.ToString());
            }
        }

        private void onQueryUpdateSucceeded(object sender, ClientRequestSucceededEventArgs args)
        {
            UpdateRecordUIMethod updateUI = DisplayInfoForUpdateRecord;
            this.Dispatcher.BeginInvoke(updateUI);
            //ddlBindData.Items.Clear();
            getData();
        }

        private void DisplayInfoForUpdateRecord()
        {
            MessageBox.Show("Item Updated Successfully");
            ddlBindData.SelectedIndex = -1;
            txtTitle.Text = "";
            txtPassword.Text = "";
            txtTitle.Focus();
        }

        private delegate void UpdateRecordUIMethod();

        private void onQueryUpdateFailed(object sender, ClientRequestFailedEventArgs args)
        {
            MessageBox.Show("Request failed. " + args.Message + "\n" + args.StackTrace);
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int itemID = int.Parse(ddlBindData.SelectedValue.ToString());
                ClientContext context = ClientContext.Current;
                Web objWeb = context.Web;
                List oList = objWeb.Lists.GetByTitle("Login");
                ListItem oListItem = oList.GetItemById(itemID);
                oListItem.DeleteObject();
                context.ExecuteQueryAsync(onQueryDeleteSucceeded, onQueryDeleteFailed);
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.ToString());
            }
        }

        private void onQueryDeleteFailed(object sender, ClientRequestFailedEventArgs args)
        {
            MessageBox.Show("Request failed. " + args.Message + "\n" + args.StackTrace);
        }


        private void onQueryDeleteSucceeded(object sender, ClientRequestSucceededEventArgs args)
        {
            DeleteRecordUIMethod updateUI = DisplayInfoForDeleteRecord;
            this.Dispatcher.BeginInvoke(updateUI);
            getData();
        }

        private void DisplayInfoForDeleteRecord()
        {
            MessageBox.Show("Item Deleted Successfully");
            ddlBindData.SelectedIndex = -1;
            txtTitle.Text = "";
            txtPassword.Text = "";
            txtTitle.Focus();
        }

        private delegate void DeleteRecordUIMethod();

       
       

       

       

       

    }
}

No comments:

Post a Comment