Wednesday, 30 January 2013

Getting Lists from SharePoint 2010 using Client Object Model (C#)



Step 1: Create New Project. (Minimum .NET Framework 3.5)
Step 2: Add “Microsoft.SharePoint.Client” and “Microsoft.SharePoint.Client.Runtime” namespaces.
Step 3: Write the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//SharePoint namespace
using Microsoft.SharePoint.Client;

namespace GettingLists
{
    class Program
    {
        static void Main(string[] args)
        {
            string siteUrl = "http://sharepointserver.com";
            ClientContext clientContext = new ClientContext(siteUrl);
            clientContext.Credentials = new System.Net.NetworkCredential("admin", "password", "sharepointserver.com");
            Web site = clientContext.Web;

            //Getting Lists
            ListCollection listCollection = site.Lists;
            clientContext.Load(listCollection);
            clientContext.ExecuteQuery();

            //Printing Lists
            foreach (List list in listCollection)
            {
                Console.WriteLine("Title: {0}", list.Title);
            }
            Console.ReadLine();
        }
    }
}


Deleting List in SharePoint 2010 using Client Object Model (C#)



Step 1: Create New Project. (Minimum .NET Framework 3.5)
Step 2: Add “Microsoft.SharePoint.Client” and “Microsoft.SharePoint.Client.Runtime” namespaces.
Step 3: Write the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//SharePoint namespace
using Microsoft.SharePoint.Client;

namespace DeletingLists
{
    class Program
    {
        static void Main(string[] args)
        {
            string siteUrl = "http://sharepointserver.com";
            ClientContext clientContext = new ClientContext(siteUrl);
            clientContext.Credentials = new System.Net.NetworkCredential("admin", "password", "sharepointserver.com");
            Web site = clientContext.Web;

            //Deleting List
            List list = site.Lists.GetByTitle("Students");
            list.DeleteObject();
            clientContext.ExecuteQuery();

            Console.WriteLine("List Deleted Successfully");
            Console.ReadLine();
        }
    }
}


Creating List in SharePoint 2010 using Client Object Model (C#)



Step 1: Create New Project. (Minimum .NET Framework 3.5)
Step 2: Add “Microsoft.SharePoint.Client” and “Microsoft.SharePoint.Client.Runtime” namespaces.
Step 3: Write the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// SharePoint namespace
using Microsoft.SharePoint.Client;

namespace ListCreation
{
    class Program
    {
        static void Main(string[] args)
        {
            string siteUrl = "http://sharepointserver.com/";
            ClientContext clientContext = new ClientContext(siteUrl);
            clientContext.Credentials = new System.Net.NetworkCredential("admin", "password", "sharepointserver.com");
            Web site = clientContext.Web;

            //Creating List
            ListCreationInformation listCreationInformation = new ListCreationInformation();
            listCreationInformation.Title = "Students";
            listCreationInformation.TemplateType = (int)ListTemplateType.GenericList;
            List list = site.Lists.Add(listCreationInformation);

            //Creating Columns
            Field firstNameField = list.Fields.AddFieldAsXml(
                @"<Field Type='Text'
                         DisplayName='First Name' />", true, AddFieldOptions.DefaultValue);

            Field lastNameField = list.Fields.AddFieldAsXml(
                @"<Field Type='Text'
                         DisplayName='Last Name' />", true, AddFieldOptions.DefaultValue);

            Field ageField = list.Fields.AddFieldAsXml(
                @"<Field Type='Number'
                         DisplayName='Age' />", true, AddFieldOptions.DefaultValue);

            clientContext.ExecuteQuery();
            Console.WriteLine("List Created Successfully");
            Console.ReadLine();
        }
    }
}


Reading Data from CSV File using C#


Step 1: Create New Project (Windows Forms Application).
Step 2: Add “System.IO” namespace.
Step 3: Create the form as follows.

Step 4: Write the following code.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ReadingCSV
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void buttonRead_Click(object sender, EventArgs e)
        {
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("First Name");
            dataTable.Columns.Add("Last Name");
            dataTable.Columns.Add("Age");
            string filePath = textBoxFilePath.Text;
            StreamReader streamReader = new StreamReader(filePath);
            string[] totalData = new string[File.ReadAllLines(filePath).Length];
            totalData = streamReader.ReadLine().Split(',');
            while (!streamReader.EndOfStream)
            {
                totalData = streamReader.ReadLine().Split(',');
                dataTable.Rows.Add(totalData[0], totalData[1], totalData[2]);
            }
            dataGridViewStudents.DataSource = dataTable;
        }
    }
}

Step 5: Output

Writing Data to CSV File using C#



Step 1: Create New Project
Step 2: Add “System.IO” namespace.
Step 3: Create the form as follows.
Step 4: Write the following code.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WritingCSV
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            string FirstName = textBoxFirstName.Text;
            string LastName = textBoxLastName.Text;
            string Age = textBoxAge.Text;
            listBoxFirstName.Items.Add(FirstName);
            listBoxLastName.Items.Add(LastName);
            listBoxAge.Items.Add(Age);
            textBoxFirstName.ResetText();
            textBoxLastName.ResetText();
            textBoxAge.ResetText();
        }

        private void buttonWrite_Click(object sender, EventArgs e)
        {
            string FilePath = textBoxFilePath.Text;
            string[] FirstNames = new string[listBoxFirstName.Items.Count];
            string[] LastNames = new string[listBoxFirstName.Items.Count];
            string[] Ages = new string[listBoxFirstName.Items.Count];
            string[] TotalData = new string[listBoxFirstName.Items.Count];
            for (int i = 0; i < listBoxFirstName.Items.Count; i++)
            {
                FirstNames[i] = listBoxFirstName.Items[i].ToString();
                LastNames[i] = listBoxLastName.Items[i].ToString();
                Ages[i] = listBoxAge.Items[i].ToString();
                TotalData[i] = FirstNames[i] + "," + LastNames[i] + "," + Ages[i];
            }
            File.WriteAllLines(FilePath, TotalData);
            MessageBox.Show("CSV File Created Successfully", "Success");
        }
    }
}

Step 5: Output




Thursday, 10 January 2013

Updating Data in Excel using C#


Step 1: Create New Project.
Step 2: Add “System.Data” and “System.Data.OleDb” namespaces.
Step 3: The connection string for accessing Excel file is
“Provider = Microsoft.ACE.OLEDB.12.0; Data Source = [Excel File Path]; Extended Properties = “Excel 12.0 Xml;HDR=YES””
Step 4: Write the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;

namespace UpdatingDataInExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            // Excel file path
            string excelFilePath = @"F:\Excel File.xlsx";
            // Connection string for accessing excel file
            string connectionString = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0}; Extended Properties=""Excel 12.0 Xml;HDR=YES""", excelFilePath);

            using (OleDbConnection Connection = new OleDbConnection(connectionString))
            {
                try
                {
                    Connection.Open();
                    using (OleDbCommand Command = new OleDbCommand())
                    {
                        Command.Connection = Connection;
                        Command.CommandText = "UPDATE [Students$] SET [First Name] = 'Sharukh', [Last Name] = 'Khan', [Age] = '40' WHERE [First Name] = 'John'";
                        int i = Command.ExecuteNonQuery();
                        Console.WriteLine("Data Updated Successfully");
                    }
                    Console.ReadLine();
                }
                catch (OleDbException ex)
                {
                    Console.WriteLine("Message: " + ex.Message);
                    Console.ReadLine();
                }
                finally
                {
                    Connection.Close();
                }
            }
        }
    }
}

Inserting Data into Excel using C#


Step 1: Create New Project.
Step 2: Add “System.Data” and “System.Data.OleDb” namespaces.
Step 3: The connection string for accessing Excel file is
“Provider = Microsoft.ACE.OLEDB.12.0; Data Source = [Excel File Path]; Extended Properties = “Excel 12.0 Xml;HDR=YES””
Step 4: Write the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;

namespace InsertingDataIntoExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            // Excel file path
            string excelFilePath = @"F:\Excel File.xlsx";
            // Connection string for accessing excel file
            string connectionString = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0}; Extended Properties=""Excel 12.0 Xml;HDR=YES""", excelFilePath);

            using (OleDbConnection Connection = new OleDbConnection(connectionString))
            {
                try
                {
                    Connection.Open();
                    using (OleDbCommand Command = new OleDbCommand())
                    {
                        Command.Connection = Connection;
                        Command.CommandText = "INSERT INTO [Students$] ([First Name], [Last Name], [Age]) VALUES ('John', 'Abraham', '34')";
                        Command.ExecuteNonQuery();
                        Console.WriteLine("Data Inserted Successfully");
                    }
                    Console.ReadLine();
                }
                catch (OleDbException ex)
                {
                    Console.WriteLine("Message: " + ex.Message);
                    Console.ReadLine();
                }
                finally
                {
                    Connection.Close();
                }
            }
        }
    }
}