Wednesday, 30 March 2022

Programmatically Copy Document Set from One site to another site

  public class ExcelManager

    {        

        public static void GenerateExcelFile(DataTable dt, string filePath)

        {

            Excel.Application xlApp = new Excel.Application();

            try

            {

                if (xlApp == null)

                {

                    Console.WriteLine("Excel is not installed in the system...");

                    return;

                }


                object misValue = System.Reflection.Missing.Value;


                Excel.Workbook xlWorkBook = xlApp.Workbooks.Add(misValue);

                Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);


                // column headings

                for (var i = 0; i < dt.Columns.Count; i++)

                {

                    xlWorkSheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;

                }


                // rows

                for (var i = 0; i < dt.Rows.Count; i++)

                {

                    // to do: format datetime values before printing

                    for (var j = 0; j < dt.Columns.Count; j++)

                    {

                        if (string.IsNullOrEmpty(Convert.ToString(dt.Rows[i][j])))

                        {

                            xlWorkSheet.Cells[i + 2, j + 1] = "";

                        }

                        else

                        {

                            xlWorkSheet.Cells[i + 2, j + 1] = Convert.ToString(dt.Rows[i][j]);

                        }

                    }

                }                

                //xlWorkSheet.Cells[1, 1] = "ID";

                //xlWorkSheet.Cells[1, 2] = "Name";

                //xlWorkSheet.Cells[2, 1] = "1001";

                //xlWorkSheet.Cells[2, 2] = "Ramakrishna";

                //xlWorkSheet.Cells[3, 1] = "1002";

                //xlWorkSheet.Cells[3, 2] = "Praveenkumar";


                xlWorkBook.SaveAs(filePath, Excel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue,

                    Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);


                xlWorkBook.Close();

                xlApp.Quit();


                Marshal.ReleaseComObject(xlWorkSheet);

                Marshal.ReleaseComObject(xlWorkBook);

                Marshal.ReleaseComObject(xlApp);


                Console.BackgroundColor = ConsoleColor.DarkBlue;

                Log.Instance.Info("Excel File: '{0}'", filePath);

                Log.Instance.Info("Excel file created successfully...");

                //Console.WriteLine("Excel file created successfully...");

                Console.BackgroundColor = ConsoleColor.Black;

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

        }


        /// <summary>

        /// Read data in excel file to datatable

        /// </summary>

        /// <param name="filename">Excel file name</param>

        /// <param name="sheetNum">Which sheet to read</param>

        /// <returns></returns>

        public System.Data.DataTable getExcelTable(string filename, int sheetNum)

        {

            Microsoft.Office.Interop.Excel.Application myExcel = new Microsoft.Office.Interop.Excel.Application();

            object missing = Missing.Value;

            Excel.Workbook myBook = myExcel.Application.Workbooks.Open(filename, missing, missing, missing,

             missing, missing, missing, missing, missing, missing,

             missing, missing, missing, missing, missing);  //open excel file

            if (myBook != null)

            {

                myExcel.Visible = false;

                Microsoft.Office.Interop.Excel.Worksheet mySheet = (Microsoft.Office.Interop.Excel.Worksheet)myBook.Worksheets[sheetNum];

                System.Data.DataTable dt = new System.Data.DataTable();

                for (int j = 1; j <= mySheet.Cells.CurrentRegion.Columns.Count; j++)

                    dt.Columns.Add();

                for (int i = 1; i <= mySheet.Cells.CurrentRegion.Rows.Count; i++)

                {

                    DataRow myRow = dt.NewRow();

                    for (int j = 1; j <= mySheet.Cells.CurrentRegion.Columns.Count; j++)

                    {

                        Microsoft.Office.Interop.Excel.Range temp = (Microsoft.Office.Interop.Excel.Range)mySheet.Cells[i, j];

                        string strValue = temp.Text.ToString();

                        myRow[j - 1] = strValue;

                    }

                    dt.Rows.Add(myRow);

                }

                myExcel.Quit();


                //The purpose of the following code is to kill the excel process, for the method Quit() can not close the excel file completely.

                System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName("EXCEL");

                foreach (System.Diagnostics.Process instance in myProcesses)

                {

                    instance.Kill();

                }

                return dt;

            }

            return null;

        }


        /// <summary>

        /// Reads an excel file and converts it into dataset with each sheet as each table of the dataset

        /// </summary>

        /// <param name="filename"></param>

        /// <param name="headers">If set to true the first row will be considered as headers</param>

        /// <returns></returns>

        public DataSet Import(string filename, bool headers = true)

        {

            DataSet dataSet = null;

            try

            {

                var _xl = new Excel.Application();

                var wb = _xl.Workbooks.Open(filename);

                var sheets = wb.Sheets;               

                if (sheets != null && sheets.Count != 0)

                {

                    dataSet = new DataSet();

                    foreach (var item in sheets)

                    {

                        var sheet = (Excel.Worksheet)item;

                        DataTable dt = null;

                        if (sheet != null)

                        {

                            dt = new DataTable();

                            var ColumnCount = ((Excel.Range)sheet.UsedRange.Rows[1, Type.Missing]).Columns.Count;

                            var rowCount = ((Excel.Range)sheet.UsedRange.Columns[1, Type.Missing]).Rows.Count;


                            for (int j = 0; j < ColumnCount; j++)

                            {

                                var cell = (Excel.Range)sheet.Cells[1, j + 1];

                                var column = new DataColumn(headers ? cell.Value : string.Empty);

                                dt.Columns.Add(column);

                            }


                            for (int i = 0; i < rowCount; i++)

                            {

                                var r = dt.NewRow();

                                for (int j = 0; j < ColumnCount; j++)

                                {

                                    var cell = (Excel.Range)sheet.Cells[i + 1 + (headers ? 1 : 0), j + 1];

                                    r[j] = cell.Value;

                                }

                                dt.Rows.Add(r);

                            }


                        }

                        dataSet.Tables.Add(dt);

                    }

                }

                _xl.Quit();

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

            return dataSet;

        }


        /// <summary>

        /// Reads an excel file from sharepoint library and copy excel content into data table

        /// </summary>

        /// <param name="context"></param>

        /// <param name="fileRelativePath"></param>

        /// <param name="SheetName"></param>

        /// <returns></returns>

        public DataTable FetchSheet(ClientContext context,string fileRelativePath, string SheetName)

        {

            DataTable dt = new DataTable();

            try

            {                               

                Microsoft.SharePoint.Client.File file = context.Web.GetFileByServerRelativeUrl(fileRelativePath);

                context.Load(file,f=>f.ListItemAllFields, f => f.ServerRelativeUrl, f => f.Title);

                context.ExecuteQuery();         

                if (file != null)

                {                    

                    var fileRef = file.ServerRelativeUrl;

                    FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, fileRef);                                                          

                    using (MemoryStream dataStream = new MemoryStream())

                    {

                        CopyStream(fileInfo.Stream, dataStream);

                        if (dataStream != null)

                        {

                            using (SpreadsheetDocument document = DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(dataStream, false))

                            {

                                Workbook workbook = document.WorkbookPart.Workbook;


                                foreach (Sheet s in document.WorkbookPart.Workbook.Descendants<Sheet>())

                                {

                                    if (s.Name.HasValue && s.Name.Value == SheetName)

                                    {

                                        WorksheetPart wsPart = document.WorkbookPart.GetPartById(s.Id) as WorksheetPart;


                                        if (wsPart == null)

                                        {

                                            continue;

                                        }

                                        Worksheet workSheet = wsPart.Worksheet;

                                        SheetData sheetData = workSheet.GetFirstChild<SheetData>();

                                        IEnumerable<Row> rows = sheetData.Descendants<Row>();


                                        foreach (Cell cell in rows.ElementAt(0))

                                        {

                                            dt.Columns.Add(GetCellValue(document, cell));

                                        }

                                        foreach (Row row in rows) //this will also include your header row...

                                        {

                                            DataRow tempRow = dt.NewRow();

                                            int columnIndex = 0;

                                            foreach (Cell cell in row.Descendants<Cell>())

                                            {

                                                // Gets the column index of the cell with data

                                                int cellColumnIndex = (int)GetColumnIndexFromName(GetColumnName(cell.CellReference));

                                                cellColumnIndex--; //zero based index

                                                if (columnIndex < cellColumnIndex)

                                                {

                                                    do

                                                    {

                                                        tempRow[columnIndex] = ""; //Insert blank data here;

                                                        columnIndex++;

                                                    }

                                                    while (columnIndex < cellColumnIndex);

                                                }

                                                tempRow[columnIndex] = GetCellValue(document, cell);


                                                columnIndex++;

                                            }

                                            dt.Rows.Add(tempRow);

                                        }

                                        dt.Rows.RemoveAt(0); //...so i'm taking it out here.                

                                    }

                                }

                            }

                        }

                    }                   

                }

            }

            catch (Exception ex)

            {

                string exString=ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

            return dt;

        }

        

        private static void CopyStream(Stream source, MemoryStream destination)

        {

            byte[] buffer = new byte[32768];

            int bytesRead;

            do

            {

                bytesRead = source.Read(buffer, 0, buffer.Length);

                destination.Write(buffer, 0, bytesRead);

            } while (bytesRead != 0);

        }


        #region Reading Excel sheet into dataset******

        public static DataTable ExtractExcelSheetValuesToDataTable(string Path)

        {

            DataTable dt = new DataTable();

            //DataSet Ds = new DataSet();

            try

            {

                using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(Path, false))

                {


                    WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;

                    IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();

                    string relationshipId = sheets.First().Id.Value;

                    WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);

                    Worksheet workSheet = worksheetPart.Worksheet;

                    SheetData sheetData = workSheet.GetFirstChild<SheetData>();

                    IEnumerable<Row> rows = sheetData.Descendants<Row>();


                    foreach (Cell cell in rows.ElementAt(0))

                    {

                        dt.Columns.Add(GetCellValue(spreadSheetDocument, cell));

                    }

                    foreach (Row row in rows) //this will also include your header row...

                    {

                        DataRow tempRow = dt.NewRow();

                        int columnIndex = 0;

                        foreach (Cell cell in row.Descendants<Cell>())

                        {

                            // Gets the column index of the cell with data

                            int cellColumnIndex = (int)GetColumnIndexFromName(GetColumnName(cell.CellReference));

                            cellColumnIndex--; //zero based index

                            if (columnIndex < cellColumnIndex)

                            {

                                do

                                {

                                    tempRow[columnIndex] = ""; //Insert blank data here;

                                    columnIndex++;

                                }

                                while (columnIndex < cellColumnIndex);

                            }

                            tempRow[columnIndex] = GetCellValue(spreadSheetDocument, cell);


                            columnIndex++;

                        }


                        dt.Rows.Add(tempRow);

                        int left = Console.CursorLeft;

                        int top = Console.CursorTop;

                        Console.SetCursorPosition(left, top);  

                        Console.ForegroundColor = ConsoleColor.White;   

                        Console.BackgroundColor = ConsoleColor.Blue;

                        Console.WriteLine(string.Format("Excel Rows Items Counts : {0}", dt.Rows.Count.ToString()));

                    }

                }

                dt.Rows.RemoveAt(0); //...so i'm taking it out here.              

                Console.ResetColor();

                Log.Instance.Trace(string.Format("Excel Rows Items Counts : {0}", dt.Rows.Count.ToString()));

                //Ds.Tables.Add(dt);

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

            return dt;

        }


        public static DataTable ExtractExcelSheetValuesToDataTable(string Path,string SheetName)

        {

            DataTable dt = new DataTable();            

            try

            {

                using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(Path,true))

                {


                    WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;

                    IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();

                    foreach (Sheet s in spreadSheetDocument.WorkbookPart.Workbook.Descendants<Sheet>())

                    {

                        if (s.Name.HasValue && s.Name.Value == SheetName)

                        {

                            string relationshipId = s.Id.Value;

                            WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);

                            Worksheet workSheet = worksheetPart.Worksheet;

                            SheetData sheetData = workSheet.GetFirstChild<SheetData>();

                            IEnumerable<Row> rows = sheetData.Descendants<Row>();


                            foreach (Cell cell in rows.ElementAt(0))

                            {

                                dt.Columns.Add(GetCellValue(spreadSheetDocument, cell));

                            }

                            foreach (Row row in rows) //this will also include your header row...

                            {

                                DataRow tempRow = dt.NewRow();

                                int columnIndex = 0;

                                foreach (Cell cell in row.Descendants<Cell>())

                                {

                                    // Gets the column index of the cell with data

                                    int cellColumnIndex = (int)GetColumnIndexFromName(GetColumnName(cell.CellReference));

                                    cellColumnIndex--; //zero based index

                                    if (columnIndex < cellColumnIndex)

                                    {

                                        do

                                        {

                                            tempRow[columnIndex] = ""; //Insert blank data here;

                                            columnIndex++;

                                        }

                                        while (columnIndex < cellColumnIndex);

                                    }

                                    tempRow[columnIndex] = GetCellValue(spreadSheetDocument, cell);


                                    columnIndex++;

                                }

                                dt.Rows.Add(tempRow);

                            }

                        }

                    }                    

                }

                dt.Rows.RemoveAt(0); //...so i'm taking it out here.                

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

            return dt;

        }


        public static string GetCellValue(SpreadsheetDocument document, Cell cell)

        {

            SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;

            if (cell.CellValue == null)

            {

                return "";

            }

            string value = cell.CellValue.InnerXml;

            if (cell.DataType != null && cell.DataType == CellValues.SharedString)

            {

                return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;

            }

            //else if (cell.DataType != null && cell.DataType == CellValues.Date)

            //{


            //    return Convert.ToString(Convert.ToDateTime(stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText));

            //}

            else

            {

                return value;

            }


        }


        /// <summary>

        /// Given just the column name (no row index), it will return the zero based column index.

        /// Note: This method will only handle columns with a length of up to two (ie. A to Z and AA to ZZ). 

        /// A length of three can be implemented when needed.

        /// </summary>

        /// <param name="columnName">Column Name (ie. A or AB)</param>

        /// <returns>Zero based index if the conversion was successful; otherwise null</returns>

        public static int? GetColumnIndexFromName(string columnName)

        {

            //return columnIndex;

            string name = columnName;

            int number = 0;

            int pow = 1;

            for (int i = name.Length - 1; i >= 0; i--)

            {

                number += (name[i] - 'A' + 1) * pow;

                pow *= 26;

            }

            return number;


        }


        /// <summary>

        /// Given a cell name, parses the specified cell to get the column name.

        /// </summary>

        /// <param name="cellReference">Address of the cell (ie. B2)</param>

        /// <returns>Column Name (ie. B)</returns>

        public static string GetColumnName(string cellReference)

        {

            // Create a regular expression to match the column name portion of the cell name.

            Regex regex = new Regex("[A-Za-z]+");

            Match match = regex.Match(cellReference);


            return match.Value;

        }



        public static void ExportDataSet(DataSet ds, string destination)

        {

            using (var workbook = SpreadsheetDocument.Create(destination, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))

            {

                var workbookPart = workbook.AddWorkbookPart();


                workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();


                workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();


                foreach (System.Data.DataTable table in ds.Tables)

                {


                    var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();

                    var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();

                    sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);


                    DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();

                    string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);


                    uint sheetId = 1;

                    if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)

                    {

                        sheetId =

                            sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;

                    }


                    DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = table.TableName };

                    sheets.Append(sheet);


                    DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();


                    List<String> columns = new List<string>();

                    foreach (System.Data.DataColumn column in table.Columns)

                    {

                        columns.Add(column.ColumnName);


                        DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();

                        cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;

                        cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);

                        headerRow.AppendChild(cell);

                    }



                    sheetData.AppendChild(headerRow);


                    foreach (System.Data.DataRow dsrow in table.Rows)

                    {

                        DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();

                        foreach (String col in columns)

                        {

                            DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();

                            cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;

                            cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //

                            newRow.AppendChild(cell);

                        }


                        sheetData.AppendChild(newRow);

                    }


                }

            }

        }


        public static void ExportDataSet(System.Data.DataTable table, string destination)

        {

            using (var workbook = SpreadsheetDocument.Create(destination, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))

            {

                var workbookPart = workbook.AddWorkbookPart();


                workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();


                workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();


                var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();

                var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();

                sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);


                DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();

                string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);


                uint sheetId = 1;

                if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)

                {

                    sheetId =

                        sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;

                }


                DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = table.TableName };

                sheets.Append(sheet);


                DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();


                List<String> columns = new List<string>();

                foreach (System.Data.DataColumn column in table.Columns)

                {

                    columns.Add(column.ColumnName);


                    DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();                    

                    //cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;

                    cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.InlineString;

                    cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);

                    headerRow.AppendChild(cell);

                }



                sheetData.AppendChild(headerRow);


                foreach (System.Data.DataRow dsrow in table.Rows)

                {

                    DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();

                    foreach (String col in columns)

                    {

                        DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();

                        //cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;

                        //cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //

                        cell.DataType = CellValues.InlineString;

                        cell.InlineString = new InlineString() { Text = new Text(dsrow[col].ToString()) };

                        newRow.AppendChild(cell);

                    }


                    sheetData.AppendChild(newRow);

                }                

            }

            Console.BackgroundColor = ConsoleColor.DarkBlue;

            Log.Instance.Info("Excel File: '{0}'", destination);

            Log.Instance.Info("Excel file created successfully...");

            //Console.WriteLine("Excel file created successfully...");

            Console.BackgroundColor = ConsoleColor.Black;

        }


        public static DataTable RemoveDuplicateRows(DataTable dTable, string colName)

        {

            Hashtable hTable = new Hashtable();

            ArrayList duplicateList = new ArrayList();


            //Add list of all the unique item value to hashtable, which stores combination of key, value pair.

            //And add duplicate item value in arraylist.

            foreach (DataRow drow in dTable.Rows)

            {

                if (hTable.Contains(drow[colName]))

                    duplicateList.Add(drow);

                else

                    hTable.Add(drow[colName], string.Empty);

            }


            //Removing a list of duplicate items from datatable.

            foreach (DataRow dRow in duplicateList)

                dTable.Rows.Remove(dRow);


            //Datatable which contains unique records will be return as output.

            return dTable;

        }

        #endregion



        #region CSV Extension Method


        public static void ToCSV(DataTable dtDataTable, string strFilePath)

        {

            StreamWriter sw = new StreamWriter(strFilePath, false);

            //headers    

            for (int i = 0; i < dtDataTable.Columns.Count; i++)

            {

                sw.Write(dtDataTable.Columns[i]);

                if (i < dtDataTable.Columns.Count - 1)

                {

                    sw.Write(",");

                }

            }

            sw.Write(sw.NewLine);

            foreach (DataRow dr in dtDataTable.Rows)

            {

                for (int i = 0; i < dtDataTable.Columns.Count; i++)

                {

                    if (!Convert.IsDBNull(dr[i]))

                    {

                        string value = dr[i].ToString();

                        if (value.Contains(','))

                        {

                            value = String.Format("\"{0}\"", value);

                            sw.Write(value);

                        }

                        else

                        {

                            sw.Write(dr[i].ToString());

                        }

                    }

                    if (i < dtDataTable.Columns.Count - 1)

                    {

                        sw.Write(",");

                    }

                }

                sw.Write(sw.NewLine);

            }

            sw.Close();

        }


        public static void SaveToCsv<T>(List<T> reportData, string path)

        {

            var lines = new List<string>();

            IEnumerable<PropertyDescriptor> props = TypeDescriptor.GetProperties(typeof(T)).OfType<PropertyDescriptor>();

            var header = string.Join(",", props.ToList().Select(x => x.Name));

            lines.Add(header);

            var valueLines = reportData.Select(row => string.Join(",", header.Split(',').Select(a => row.GetType().GetProperty(a).GetValue(row, null))));

            lines.AddRange(valueLines);

            System.IO.File.WriteAllLines(path, lines.ToArray());

        }

        public static void ExportDataTableToCSV(DataTable dt,string csvfilePath)

        {

            try

            {

                StringBuilder sb = new StringBuilder();


                IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().

                                                  Select(column => column.ColumnName);

                sb.AppendLine(string.Join(",", columnNames));


                foreach (DataRow row in dt.Rows)

                {

                    IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());

                    sb.AppendLine(string.Join(",", fields));

                }


                System.IO.File.WriteAllText(csvfilePath, sb.ToString());


            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

        }


        public static void CreateFastCSVFile(DataTable table, string strFilePath)

        {

            const int capacity = 5000000;

            const int maxCapacity = 20000000;


            //First we will write the headers.

            StringBuilder csvBuilder = new StringBuilder(capacity);

            csvBuilder.AppendLine(string.Join(",", table.Columns.Cast<DataColumn>().Select(c => c.ColumnName)));


            // Create the CSV file and write all from StringBuilder

            using (var sw = new StreamWriter(strFilePath, false))

            {

                foreach (DataRow dr in table.Rows)

                {

                    if (csvBuilder.Capacity >= maxCapacity)

                    {

                        sw.Write(csvBuilder.ToString());

                        csvBuilder = new StringBuilder(capacity);

                    }

                    csvBuilder.Append(String.Join(",", dr.ItemArray));

                }

                sw.Write(csvBuilder.ToString());

            }

        }

        public static DataTable ConvertCSVtoDataTable(string strFilePath)

        {

            string Fulltext;            

            DataTable dtCsv = new DataTable();

            using (StreamReader sr = new StreamReader(strFilePath))

            {

                while (!sr.EndOfStream)

                {

                    Fulltext = sr.ReadToEnd().ToString(); //read full file text  

                    string[] rows = Fulltext.Split('\n'); //split full file text into rows  

                    for (int i = 0; i < rows.Count() - 1; i++)

                    {

                        Regex regx = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");

                        //string[] rowValues = rows[i].Split(','); //split each row with comma to get individual values  

                        string[] rowValues = regx.Split(rows[i]); //split each row with comma to get individual values  

                        {

                            if (i == 0)

                            {

                                for (int j = 0; j < rowValues.Count(); j++)

                                {

                                    string header = rowValues[j].Replace("\"", "");

                                    //dtCsv.Columns.Add(rowValues[j]); //add headers  

                                    dtCsv.Columns.Add(header); //add headers  

                                }

                            }

                            else

                            {

                                DataRow dr = dtCsv.NewRow();

                                for (int k = 0; k < rowValues.Count(); k++)

                                {

                                    string cellValue = rowValues[k].Replace("\"", "");

                                    //dr[k] = Convert.ToString(rowValues[k]);

                                    dr[k] = Convert.ToString(cellValue);

                                }

                                dtCsv.Rows.Add(dr); //add other rows  

                            }

                        }

                    }

                }

            }

            return dtCsv;

        }

        public static DataTable ConvertCSVTexttoDataTable(string Fulltext)

        {

            DataTable dtCsv = new DataTable();

            string[] rows = Fulltext.Split('\n'); //split full file text into rows  

            for (int i = 0; i < rows.Count() - 1; i++)

            {

                Regex regx = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");

                //string[] rowValues = rows[i].Split(','); //split each row with comma to get individual values  

                string[] rowValues = regx.Split(rows[i]); //split each row with comma to get individual values  

                {

                    if (i == 0)

                    {

                        for (int j = 0; j < rowValues.Count(); j++)

                        {

                            string header = rowValues[j].Replace("\"", "");

                            //dtCsv.Columns.Add(rowValues[j]); //add headers  

                            dtCsv.Columns.Add(header); //add headers  

                        }

                    }

                    else

                    {

                        DataRow dr = dtCsv.NewRow();

                        for (int k = 0; k < rowValues.Count(); k++)

                        {

                            string cellValue = rowValues[k].Replace("\"", "");

                            //dr[k] = Convert.ToString(rowValues[k]);

                            dr[k] = Convert.ToString(cellValue);

                        }

                        dtCsv.Rows.Add(dr); //add other rows  

                    }

                }

            }

            return dtCsv;

        }

        public static DataTable ReadCsvFile(ClientContext context, string fileRelativePath)

        {

            DataTable dtCsv = new DataTable();

            try

            {

                Microsoft.SharePoint.Client.File file = context.Web.GetFileByServerRelativeUrl(fileRelativePath);

                context.Load(file, f => f.ListItemAllFields, f => f.ServerRelativeUrl, f => f.Title,f=>f.Name);

                context.ExecuteQuery();

                if (file != null)

                {

                    string Fulltext;

                    var fileRef = file.ServerRelativeUrl;

                    FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, fileRef);

                    //ClientResult<Stream> fileInfo = file.OpenBinaryStream();

                    //context.Load(file);

                    context.ExecuteQuery();

                    using (MemoryStream datastream = new MemoryStream())

                    {

                        //fileInfo.Stream.CopyTo(datastream);

                        //datastream.ToArray();

                        if (datastream != null)

                        {

                            using (StreamReader sr = new StreamReader(fileInfo.Stream, Encoding.UTF8))

                            {

                                while (!sr.EndOfStream)

                                {

                                    Fulltext = sr.ReadToEnd().ToString(); //read full file text  

                                    string[] rows = Fulltext.Split('\n'); //split full file text into rows  

                                    for (int i = 0; i < rows.Count() - 1; i++)

                                    {

                                        Regex regx = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");

                                        //string[] rowValues = rows[i].Split(','); //split each row with comma to get individual values  

                                        string[] rowValues = regx.Split(rows[i]); //split each row with comma to get individual values  

                                        {

                                            if (i == 0)

                                            {

                                                for (int j = 0; j < rowValues.Count(); j++)

                                                {

                                                    string header = rowValues[j].Replace("\"", "");

                                                    //dtCsv.Columns.Add(rowValues[j]); //add headers  

                                                    dtCsv.Columns.Add(header); //add headers  

                                                }

                                            }

                                            else

                                            {

                                                DataRow dr = dtCsv.NewRow();

                                                for (int k = 0; k < rowValues.Count(); k++)

                                                {

                                                    string cellValue = rowValues[k].Replace("\"", "");

                                                    //dr[k] = Convert.ToString(rowValues[k]);

                                                    dr[k] = Convert.ToString(cellValue);

                                                }

                                                dtCsv.Rows.Add(dr); //add other rows  

                                            }

                                        }

                                    }

                                }

                            }

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

            return dtCsv;

        }


        public static void ConvertCSVtoExcel(string filePath)

        {

            Excel.Application xlApp = new Excel.Application();

            string fileName = string.Format("{0}.{1}", Path.GetFileNameWithoutExtension(filePath), "xlsx");

            string xlsfilePath = @"C:\Exported Documents\Export Files Information\" + fileName;

            try

            {

                if (xlApp == null)

                {

                    Console.WriteLine("Excel is not installed in the system...");

                    return;

                }


                object misValue = System.Reflection.Missing.Value;


                Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(filePath);

                Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

                Excel.Range used = xlWorkSheet.UsedRange;

                used.EntireColumn.AutoFit();

                xlWorkBook.SaveAs(xlsfilePath, Excel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue,

                    Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);                

                xlWorkBook.Close();

                xlApp.Quit();


                Marshal.ReleaseComObject(xlWorkSheet);

                Marshal.ReleaseComObject(xlWorkBook);

                Marshal.ReleaseComObject(xlApp);


                Console.BackgroundColor = ConsoleColor.DarkBlue;

                Log.Instance.Info("Excel File: '{0}'", xlsfilePath);

                Log.Instance.Info("Excel file created successfully...");

                //Console.WriteLine("Excel file created successfully...");

                Console.BackgroundColor = ConsoleColor.Black;

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

        }

        #endregion

    }

##############################################

 public class csomListCommon

    {

        /// <summary>

        /// DESC: Add new record in list

        /// </summary>

        /// <param name="clientContext"></param>

        /// <param name="ListName"></param>

        /// <param name="id"></param>

        /// <param name="listItemFieldValue"></param>

        public static void createListItem(ClientContext clientContext, string ListName, Dictionary<string, object> listItemFieldValue)

        {

            try

            {

                if (clientContext.Web.ListExists(ListName))

                {

                    List oList = clientContext.Web.Lists.GetByTitle(ListName);

                    clientContext.Load(oList.Fields, fc => fc.Where(f => f.Hidden == false && f.ReadOnlyField == false && f.InternalName != "Attachments" && f.InternalName != "ContentType"));

                    clientContext.ExecuteQuery();

                    ListItemCreationInformation listCreationInformation = new ListItemCreationInformation();

                    ListItem oListItem = oList.AddItem(listCreationInformation);                    

                    foreach (var field in oList.Fields)

                    {

                        object newvalue;

                        listItemFieldValue.TryGetValue(field.InternalName, out newvalue);

                        oListItem[field.InternalName] = newvalue;

                    }

                    oListItem.Update();

                    clientContext.ExecuteQuery();

                }

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

        }

        /// <summary>

        /// Desc: Update any record of list by item id.

        /// </summary>

        /// <param name="clientContext"></param>

        /// <param name="ListName"></param>

        /// <param name="id"></param>

        /// <param name="listItemFieldValue">Use listitem of fieldvalue</param>

        public static void updateListItemById(ClientContext clientContext, string ListName, int id, Dictionary<string, object> listItemFieldValue)

        {

            try

            {

                if (clientContext.Web.ListExists(ListName))

                {

                    List oList = clientContext.Web.Lists.GetByTitle(ListName);

                    clientContext.Load(oList.Fields, fc => fc.Where(f => f.Hidden == false && f.ReadOnlyField == false && f.InternalName != "Attachments" && f.InternalName != "ContentType"));

                    clientContext.ExecuteQuery();

                    ListItem oListItem = oList.GetItemById(id);

                    foreach (var field in oList.Fields)

                    {

                        object newvalue;

                        listItemFieldValue.TryGetValue(field.InternalName, out newvalue);

                        oListItem[field.InternalName] = newvalue;

                    }

                    oListItem.Update();

                    clientContext.ExecuteQuery();

                }

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

        }


        /// <summary>

        /// Desc: get all list items from any large list to call this function

        /// </summary>

        /// <param name="ctx"></param>

        /// <param name="ListName"></param>

        /// <param name="FieldName">Its column name where apply filter condition</param>

        /// <param name="FieldValue">value of filter</param>

        /// <returns></returns>

        public static List<ListItem> getSharePointListItems(ClientContext ctx, string ListName,string FieldName,string FieldValue)

        {

            //Creating a single buffer for storing all the ListItems

            List<ListItem> lstListItemCollection = new List<ListItem>();

            try

            {

                int limit = int.Parse(Appsetting.rowLimits);

                List list = ctx.Web.Lists.GetByTitle(ListName);


                CamlQuery camlQuery = new CamlQuery();

                camlQuery.ViewXml = string.Format(CAML.ViewQuery(ViewScope.RecursiveAll,

                                                            CAML.Where(

                                                                CAML.Eq(

                                                                    CAML.FieldValue("{0}", "Text", "{1}")

                                                                    )

                                                                    ),

                                                            CAML.OrderBy(

                                                                new OrderByField("ID", false)

                                                                ),

                                                            rowLimit: limit), FieldName, FieldValue);


                int intIndex = 1;               

                do

                {

                    ListItemCollection listItemCollection = list.GetItems(camlQuery);

                    ctx.Load(listItemCollection);

                    ctx.ExecuteQuery();


                    //Adding the current set of ListItems in our single buffer

                    lstListItemCollection.AddRange(listItemCollection);


                    //Reset the current pagination info

                    camlQuery.ListItemCollectionPosition = listItemCollection.ListItemCollectionPosition;


                    Console.WriteLine("Page:: " + intIndex++);

                    Console.WriteLine("ListItemCollectionPosition:: " + camlQuery.ListItemCollectionPosition);


                } while (camlQuery.ListItemCollectionPosition != null);

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

            return lstListItemCollection;

        }


        /// <summary>

        /// Desc: Async to get all list items from any large list to call this function

        /// </summary>

        /// <param name="actx"></param>

        /// <param name="ListName"></param>

        /// <param name="FieldName"></param>

        /// <param name="FieldValue"></param>

        /// <returns></returns>

        public async Task<List<ListItem>> GetSharePointDataAsync(ClientContext actx,string ListName, string FieldName, string FieldValue)

        {

            List<Task> tasks = new List<Task>();

            List listObject = actx.Web.Lists.GetByTitle(ListName);

            actx.Load(listObject);

            actx.ExecuteQuery();

            int rowlimit = int.Parse(Appsetting.rowLimits);

            List<ListItemCollection> colslistObject = new List<ListItemCollection>();

            ListItemCollectionPosition poslistObject = null;

            List<ListItem> itemslistObject = new List<ListItem>();

            CamlQuery query = new CamlQuery();

            //CamlQuery query = new CamlQuery() { ViewXml = "<View><RowLimit>" + rowlimit + "</RowLimit></View>" };

            query.ViewXml = string.Format(CAML.ViewQuery(ViewScope.RecursiveAll,

                                                           CAML.Where(

                                                               CAML.Eq(

                                                                   CAML.FieldValue("{0}", "Text", "{1}")

                                                                   )

                                                                   ),

                                                           CAML.OrderBy(

                                                               new OrderByField("ID", false)

                                                               ),

                                                           rowLimit: rowlimit), FieldName, FieldValue);

            int positioncount = 0;

            do

            {

                query.ListItemCollectionPosition = poslistObject;

                colslistObject.Add(listObject.GetItems(query));

                actx.Load(colslistObject.Last());

                tasks.Add(actx.ExecuteQueryAsync());

                positioncount += rowlimit;

                if (positioncount > listObject.ItemCount)

                {

                    poslistObject = null;

                }

                else

                {

                    poslistObject = new ListItemCollectionPosition { PagingInfo = "Paged=TRUE&p_ID=" + positioncount };

                }

            } while (poslistObject != null);

            await Task.WhenAll(tasks);

            return itemslistObject;

        }


        /// <summary>

        /// Desc: Async get all list items from any large list to call this function without any condition

        /// </summary>

        /// <param name="actx"></param>

        /// <param name="ListName"></param>

        /// <returns></returns>

        public static async Task<List<ListItemCollection>> GetSharePointDataAsync(ClientContext actx, string ListName)

        {

            List<Task> tasks = new List<Task>();

            List listObject = actx.Web.Lists.GetByTitle(ListName);

            actx.Load(listObject);

            actx.ExecuteQuery();

            int rowlimit = int.Parse(Appsetting.rowLimits);

            List<ListItemCollection> colslistObject = new List<ListItemCollection>();

            ListItemCollectionPosition poslistObject = null;

            //List<ListItem> itemslistObject = new List<ListItem>();

            CamlQuery query = new CamlQuery();

            //CamlQuery query = new CamlQuery() { ViewXml = "<View><RowLimit>" + rowlimit + "</RowLimit></View>" };

            query.ViewXml = CAML.ViewQuery(ViewScope.RecursiveAll,

                                                           string.Empty,

                                                           CAML.OrderBy(

                                                               new OrderByField("ID", false)

                                                               ),

                                                           rowLimit: rowlimit);

            int positioncount = 0;

            int left = Console.CursorLeft;

            int top = Console.CursorTop;

            do

            {

                query.ListItemCollectionPosition = poslistObject;

                colslistObject.Add(listObject.GetItems(query));

                actx.Load(colslistObject.Last());

                tasks.Add(actx.ExecuteQueryAsync());

                positioncount += rowlimit;

                if (positioncount > listObject.ItemCount)

                {

                    poslistObject = null;

                }                

                else

                {

                    poslistObject = new ListItemCollectionPosition { PagingInfo = "Paged=TRUE&p_ID=" + positioncount };

                    Console.SetCursorPosition(left, top);

                    Console.ForegroundColor = ConsoleColor.Yellow;                    

                    Console.WriteLine(string.Format("Total Item Count: {0}", positioncount.ToString()));

                }

            } while (poslistObject != null);

            await Task.WhenAll(tasks);       

            Console.ResetColor();

            return colslistObject;

        }

    }

#######################################################

public static class FolderExtensions

    {

        private static int filesCount = 0;

        public static void CopyFilesTo(this Folder folder, string folderUrl)

        {

            bool isOverwrite = true;

            var ctx = (ClientContext)folder.Context;

            if (!ctx.Web.IsPropertyAvailable("ServerRelativeUrl"))

            {

                ctx.Load(ctx.Web, w => w.ServerRelativeUrl);

            }

            ctx.Load(folder, f => f.Files, f => f.ServerRelativeUrl, f => f.Folders);

            ctx.ExecuteQuery();

            //Ensure target folder exists

            EnsureFolder(ctx.Web.RootFolder, folderUrl.Replace(ctx.Web.ServerRelativeUrl, string.Empty));

            foreach (var file in folder.Files)

            {

                var targetFileUrl = file.ServerRelativeUrl.Replace(folder.ServerRelativeUrl, folderUrl);

                //file.MoveTo(targetFileUrl, MoveOperations.Overwrite);

                file.CopyTo(targetFileUrl, isOverwrite);

            }

            ctx.ExecuteQuery();

            foreach (var subFolder in folder.Folders)

            {

                var targetFolderUrl = subFolder.ServerRelativeUrl.Replace(folder.ServerRelativeUrl, folderUrl);

                subFolder.CopyFilesTo(targetFolderUrl);

            }

        }

        public static void MoveFilesTo(this Folder folder, string folderUrl)

        {

            var ctx = (ClientContext)folder.Context;

            if (!ctx.Web.IsPropertyAvailable("ServerRelativeUrl"))

            {

                ctx.Load(ctx.Web, w => w.ServerRelativeUrl);

            }

            ctx.Load(folder, f => f.Files, f => f.ServerRelativeUrl, f => f.Folders);

            ctx.ExecuteQuery();

            //Ensure target folder exists

            EnsureFolder(ctx.Web.RootFolder, folderUrl.Replace(ctx.Web.ServerRelativeUrl, string.Empty));

            foreach (var file in folder.Files)

            {

                var targetFileUrl = file.ServerRelativeUrl.Replace(folder.ServerRelativeUrl, folderUrl);

                file.MoveTo(targetFileUrl, MoveOperations.Overwrite);

            }

            ctx.ExecuteQuery();

            foreach (var subFolder in folder.Folders)

            {

                var targetFolderUrl = subFolder.ServerRelativeUrl.Replace(folder.ServerRelativeUrl, folderUrl);

                subFolder.MoveFilesTo(targetFolderUrl);

            }

        }

        public static Folder EnsureFolder(Folder parentFolder, string folderUrl)

        {

            var ctx = parentFolder.Context;

            var folderNames = folderUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            var folderName = folderNames[0];

            var folder = parentFolder.Folders.Add(folderName);

            ctx.Load(folder);

            ctx.ExecuteQuery();

            if (folderNames.Length > 1)

            {

                var subFolderUrl = string.Join("/", folderNames, 1, folderNames.Length - 1);

                return EnsureFolder(folder, subFolderUrl);

            }

            return folder;

        }


        public static void CopyAllFilesToCrossSite(string SourceSiteURL, string TargetSiteURL, string SourceLibraryName, string TargetLibraryName, string docSetContentType = null)

        {

            Uri sourcesiteURi = new Uri(SourceSiteURL);

            Uri targetsiteURi = new Uri(TargetSiteURL);

            Log.Instance.Trace("start to load all source library and target library.");


            bool isSourceAuthenticated = false, isTargetAuthenticated = false;

            //bool isSourceAuthenticated = true, isTargetAuthenticated = true;

            FieldCollection Sourcefields = null, Targetfields = null;

            List SourceLibrary = null, TargetLibrary = null;

            Folder SourceFolder = null, TargetFolder = null;


            Log.Instance.Debug("Start to get source site connection.");

            //ClientContext SourceCtx = Appsetting.pnpauthManager.pnp_AuthenticateApponly(sourcesiteURi, Appsetting.ClientId_Prod_Source, Appsetting.ClientSecret_Prod_Source, ref isSourceAuthenticated);

            //ClientContext SourceCtx = Appsetting.pnpauthManager.pnp_AuthenticateApponly(sourcesiteURi, Appsetting.ClientId_Prod_Traget, Appsetting.ClientSecret_Prod_Target, ref isSourceAuthenticated);

            ClientContext SourceCtx = Appsetting.pnpauthManager.pnp_AuthenticateApponly(sourcesiteURi, Appsetting.ClientId_DEV, Appsetting.ClientSecret_DEV, ref isSourceAuthenticated);            

            //ClientContext SourceCtx = Appsetting.pnpauthManager.pnp_AuthenticateUser(sourcesiteURi, PnPAuthenticationManager.EnviromentValue.o365);

            SourceCtx.Load(SourceCtx.Web);

            SourceCtx.Load(SourceCtx.Web.Lists);

            SourceCtx.ExecuteQuery();

            Log.Instance.Info("Done! source site connection.");


            Log.Instance.Debug("Start to get target site connection.");

            System.Threading.Thread.Sleep(200);

            ClientContext TargetCtx = Appsetting.pnpauthManager.pnp_AuthenticateApponly(targetsiteURi, Appsetting.ClientId_INT, Appsetting.ClientSecret_INT, ref isTargetAuthenticated);

            //ClientContext TargetCtx = Appsetting.pnpauthManager.pnp_AuthenticateApponly(targetsiteURi, Appsetting.ClientId_INT, Appsetting.ClientSecret_INT, ref isTargetAuthenticated);

            //ClientContext TargetCtx = Appsetting.pnpauthManager.pnp_AuthenticateUser(targetsiteURi, PnPAuthenticationManager.EnviromentValue.o365);

            TargetCtx.Load(TargetCtx.Web);

            TargetCtx.Load(TargetCtx.Web.Lists);

            TargetCtx.ExecuteQuery();

            Log.Instance.Info("Done! target site connection.");


            //SourceCtx.RequestTimeout = System.Threading.Timeout.Infinite;

            //TargetCtx.RequestTimeout = System.Threading.Timeout.Infinite;


            if (isSourceAuthenticated && isTargetAuthenticated)

            {

                if (SourceCtx.Web.ListExists(SourceLibraryName))

                {

                    SourceLibrary = SourceCtx.Web.Lists.GetByTitle(SourceLibraryName);

                    SourceCtx.Load(SourceLibrary);

                    SourceCtx.Load(SourceLibrary.RootFolder);

                    SourceCtx.Load(SourceLibrary.Fields, fc => fc.Where(f => f.Hidden == false && f.ReadOnlyField == false && f.InternalName != "Attachments" && f.InternalName != "ContentType"));

                    SourceCtx.ExecuteQuery();

                    if (SourceLibrary.Fields != null)

                        Sourcefields = SourceLibrary.Fields;

                    if (SourceLibrary.RootFolder != null)

                        SourceFolder = SourceLibrary.RootFolder;

                }

                else

                {

                    Log.Instance.Warn("Source library '{0}' does not exist. Please check!", SourceLibraryName);

                }


                if (TargetCtx.Web.ListExists(SourceLibraryName))

                {

                    TargetLibrary = TargetCtx.Web.Lists.GetByTitle(TargetLibraryName);

                    TargetCtx.Load(TargetLibrary);

                    TargetCtx.Load(TargetLibrary.RootFolder);

                    TargetCtx.Load(TargetLibrary.Fields, fc => fc.Where(f => f.Hidden == false && f.ReadOnlyField == false && f.InternalName != "Attachments" && f.InternalName != "ContentType"));

                    TargetCtx.ExecuteQuery();

                    if (TargetLibrary.Fields != null)

                        Targetfields = TargetLibrary.Fields;


                    if (TargetLibrary.RootFolder != null)

                        TargetFolder = TargetLibrary.RootFolder;

                }

                else

                {

                    Log.Instance.Warn("Target library '{0}' does not exist. Please check!", TargetLibraryName);

                }

                Log.Instance.Debug("Start to Copy All Files With Metadata to target site.");

                List<Common.ExcelFileInformation> lstexcelFileInformation = new List<Common.ExcelFileInformation>();

                CopyAllFilesWithMetadata(SourceCtx, TargetCtx, SourceLibrary, TargetLibrary, SourceFolder, TargetFolder, Sourcefields, Targetfields, lstexcelFileInformation, docSetContentType);


                if (lstexcelFileInformation != null && lstexcelFileInformation.Count() > 0)

                {

                    string csvFilePath = @"C:\Exported Documents\Export Files Information\" + "" + string.Format("{0}_{1}.csv", TargetLibraryName, DateTime.Now.ToString("MM-dd-yyyy hh-mm"));

                    Log.Instance.Debug(string.Format("start to copying all folders and files information to csv files as given path. \n CSV File Path: {0}", csvFilePath));

                    try

                    {

                        System.Data.DataTable dt = MakeDataTable.ToProcessDataTable<Common.ExcelFileInformation>(lstexcelFileInformation, Targetfields);

                        Log.Instance.Debug(string.Format("Processing to build csv file. Please wait..."));

                        ExcelManager.ToCSV(dt, csvFilePath);

                        Log.Instance.Info(string.Format("Done! to load all folders and files information to csv files as given path. \n CSV File Path: {0}", csvFilePath));

                    }

                    catch (Exception ex)

                    {

                        string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                        Log.Instance.Error(exString);

                    }

                }

            }

        }

        public static void CopyAllFilesWithMetadata(ClientContext SourceCtx, ClientContext TargetCtx, List SourceLibrary, List TargetLibrary, Folder SourceFolder, Folder TargetFolder, FieldCollection Sourcefields, FieldCollection Targetfields, List<Common.ExcelFileInformation> listExcelFileInformation, string docSetContentType = null)

        {

            try

            {

                //Get all Files from the source folder

                Log.Instance.Trace("Get all Files from the source folder");

                var SourceFilesColl = SourceFolder.Files;                

                SourceCtx.Load(SourceFilesColl);                

                SourceCtx.ExecuteQuery();


                // Iterate through each file and copy

                Log.Instance.Trace("Start to Iterate through each file and copy...");


                foreach (Microsoft.SharePoint.Client.File SourceFile in SourceFilesColl)

                {

                    try

                    {

                        //Get the source file

                        //var FileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(SourceCtx, SourceFile.ServerRelativeUrl);


                        var fileStreamResult = SourceFile.OpenBinaryStream();

                        SourceCtx.Load(SourceFile);

                        SourceCtx.Load(SourceFile,f => f, f => f.ListItemAllFields);

                        SourceCtx.ExecuteQuery();


                        //var FileInfo = fileStreamResult.Value;

                        //Copy File to the Target location

                        string TargetFileURL = TargetFolder.ServerRelativeUrl + "/" + SourceFile.Name;

                        //Microsoft.SharePoint.Client.File.SaveBinaryDirect(TargetCtx, TargetFileURL, FileInfo.Stream, true);


                        MemoryStream datastream = new MemoryStream();

                        fileStreamResult.Value.CopyTo(datastream);

                        UploadFileToSharePoint(TargetCtx, TargetLibrary, TargetFolder, datastream, SourceFile.Name);


                        //Copy Metadata field values

                        var SourceListItem = SourceFile.ListItemAllFields;

                        SourceFolder.Context.Load(SourceListItem);

                        SourceFolder.Context.ExecuteQuery();


                        if (!string.IsNullOrEmpty(TargetFileURL))

                        {

                            //Get the new file created

                            var TargetFile = TargetCtx.Web.GetFileByServerRelativeUrl(TargetFileURL);

                            if (TargetFile != null)

                            {

                                TargetCtx.Load(TargetFile, f => f, f => f.ListItemAllFields);                                

                                TargetCtx.ExecuteQuery();

                                if (TargetFile.ListItemAllFields != null)

                                {

                                    ListItem TargetListItem = TargetFile.ListItemAllFields;


                                    Log.Instance.Info("Copied File '{0}' to '{1}'", SourceFile.ServerRelativeUrl, TargetFileURL);

                                    //Set Metadata values from the source                        

                                    Sourcefields.Cast<Field>().ToList().ForEach(sf =>

                                    {

                                        string srcFieldName = sf.Title;

                                        string srcFieldInternalName = sf.InternalName;

                                        if (SourceListItem.FieldValues.ContainsKey(srcFieldInternalName))

                                        {

                                            if (TargetListItem.FieldValues.ContainsKey(srcFieldInternalName))

                                            {

                                                TargetListItem[srcFieldInternalName] = SourceListItem.FieldValues[srcFieldInternalName];

                                            }

                                        }

                                    });

                                    try

                                    {

                                        var Author = TargetCtx.Web.EnsureUser(((FieldUserValue)SourceListItem["Author"]).Email);

                                        TargetListItem["Author"] = Author;

                                        TargetListItem["Created"] = SourceListItem["Created"];

                                        if (!string.IsNullOrEmpty(((FieldUserValue)SourceListItem["Editor"]).Email))

                                        {

                                            if (((FieldUserValue)SourceListItem["Editor"]).Email.Equals("SharePoint App", StringComparison.OrdinalIgnoreCase))

                                            {

                                                var Editor = TargetCtx.Web.EnsureUser("DPandey@munichre.com");

                                                TargetListItem["Editor"] = Editor;

                                            }

                                            else

                                            {

                                                var Editor = TargetCtx.Web.EnsureUser(((FieldUserValue)SourceListItem["Editor"]).Email);

                                                TargetListItem["Editor"] = Editor;

                                            }

                                        }                                                                               

                                        TargetListItem["Modified"] = SourceListItem["Modified"];

                                        TargetListItem.Update();

                                        TargetCtx.ExecuteQuery();

                                    }

                                    catch (Exception ex)

                                    {

                                        string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                                        Log.Instance.Error(exString);

                                    }

                                    //batchIndex++;

                                    //if (batchIndex == batchexecuteSize)

                                    //{

                                    //    TargetCtx.ExecuteQuery();

                                    //    isExecuteQueryRun = true;

                                    //    batchIndex = 0;

                                    //}

                                    //TargetCtx.ExecuteQuery();                        


                                    #region audit excel information

                                    TargetCtx.Load(TargetListItem);

                                    TargetCtx.ExecuteQuery();

                                    Common.ExcelFileInformation excelFileInformation = getExcelFileInformation(TargetCtx, TargetListItem, TargetLibrary.Title);

                                    if (excelFileInformation != null)

                                    {

                                        listExcelFileInformation.Add(excelFileInformation);

                                    }

                                    #endregion

                                }

                            }

                        }

                    }

                    catch (Exception ex)

                    {

                        string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                        Log.Instance.Error(exString);

                    }

                }

                //if (isExecuteQueryRun == false)

                //{

                //    TargetCtx.ExecuteQuery();

                //}

                if (listExcelFileInformation != null)

                {

                    if (listExcelFileInformation.Count > 0)

                    {

                        if (filesCount == 1200)

                        {

                            Log.Instance.Debug("Total File has been copying to Dev Environment. Count: " + filesCount.ToString());

                            Log.Instance.Trace("Total Excel File has been copying to Dev Environment. Count: " + listExcelFileInformation.Count.ToString());

                            Console.Read();

                            return;

                        }

                        else

                        {

                            //string csvFilePath = @"C:\Users\ny601238\OneDrive - Munich Re\Documents\Visual Studio 2015\Projects\Migration Document\" + "" + string.Format("{0}_{1}.csv", TargetLibrary.Title, DateTime.Now.ToString("MM-dd-yyyy hh-mm"));

                            //Log.Instance.Debug(string.Format("start to copying all folders and files information to csv files as given path. \n CSV File Path: {0}", csvFilePath));

                            //try

                            //{

                            //    System.Data.DataTable dt = MakeDataTable.ToProcessDataTable<Common.ExcelFileInformation>(listExcelFileInformation, Targetfields);

                            //    Log.Instance.Debug(string.Format("Processing to build csv file. Please wait..."));

                            //    ExcelManager.ToCSV(dt, csvFilePath);

                            //    Log.Instance.Info(string.Format("Done! to load all folders and files information to csv files as given path. \n CSV File Path: {0}", csvFilePath));

                            //}

                            //catch (Exception ex)

                            //{

                            //    string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                            //    Log.Instance.Error(exString);

                            //}

                            Log.Instance.Debug("Total File has been copying to Dev Environment. Count: " + filesCount.ToString());

                            Log.Instance.Trace("Total Excel File has been copying to Dev Environment. Count: " + listExcelFileInformation.Count.ToString());

                        }

                    }

                }

                //Process Sub Folders

                var SubFolders = SourceFolder.Folders;

                SourceFolder.Context.Load(SubFolders);

                SourceFolder.Context.ExecuteQuery();

                foreach (var SubFolder in SubFolders)

                {

                    if (SubFolder.Name != "Forms")

                    {

                        //ProgId = SubFolder.ProgId

                        //Prepare Target Folder

                        Microsoft.SharePoint.Client.Folder currFolder = null;

                        string TargetFolderURL = StringUtility.ReplaceString(SubFolder.ServerRelativeUrl, SourceLibrary.RootFolder.ServerRelativeUrl, TargetLibrary.RootFolder.ServerRelativeUrl);

                        try

                        {

                            currFolder = TargetCtx.Web.GetFolderByServerRelativeUrl(TargetFolderURL);

                            TargetFolder.Context.Load(currFolder);

                            TargetFolder.Context.ExecuteQuery();

                        }

                        catch

                        {

                            // Create Folder

                            if (currFolder.ServerObjectIsNull == null)

                            {

                                SourceFolder.Context.Load(SubFolder);

                                SourceFolder.Context.Load(SubFolder.ListItemAllFields);

                                SourceFolder.Context.ExecuteQuery();

                                //if (ProgId - eq "Sharepoint.DocumentSet") {

                                if (SubFolder.ListItemAllFields.FieldValues.ContainsKey("HTML_x0020_File_x0020_Type"))

                                {

                                    string HtmlFieldType = Convert.ToString(SubFolder.ListItemAllFields.FieldValues["HTML_x0020_File_x0020_Type"]);

                                    SourceFolder.Context.Load(SubFolder.ListItemAllFields.ContentType);

                                    SourceFolder.Context.ExecuteQuery();

                                    var contetTypeId = SubFolder.ListItemAllFields.ContentType.Id;

                                    var currcontetTypeName = SubFolder.ListItemAllFields.ContentType.Name;

                                    Log.Instance.Debug(string.Format("Folder Name: {0} and Content type: {1}", SubFolder.Name, currcontetTypeName));

                                    //    Write - Host "(ProgId) Document Set Added:" SubFolder.Name - f Yellow

                                    if (string.IsNullOrEmpty(docSetContentType))

                                        docSetContentType = "";

                                    if (HtmlFieldType == "Sharepoint.DocumentSet" || currcontetTypeName.ToLower() == docSetContentType.ToLower())

                                    {

                                        //bool isDSCreated=Task.Run(() => DocumentLibrary.createNewDocumentSet(TargetCtx, TargetLibrary.Title, SubFolder.Name)).GetAwaiter().GetResult();

                                        Microsoft.SharePoint.Client.Folder newDSfolder = createNewDocumentSet(TargetCtx, SubFolder, TargetFolder, TargetLibrary.Title, SubFolder.Name);

                                        if (newDSfolder != null)

                                        {

                                            System.Threading.Thread.Sleep(100);

                                            updateDocumentSetMetaData(SourceCtx, TargetCtx, SubFolder, newDSfolder, Sourcefields, Targetfields);


                                            #region audit excel information

                                            TargetCtx.Load(newDSfolder.ListItemAllFields);

                                            TargetCtx.ExecuteQuery();

                                            Common.ExcelFileInformation excelFileInformation = getExcelFileInformation(TargetCtx, newDSfolder.ListItemAllFields, TargetLibrary.Title);

                                            if (excelFileInformation != null)

                                            {

                                                listExcelFileInformation.Add(excelFileInformation);

                                            }

                                            #endregion


                                            CopyAllFilesWithMetadata(SourceCtx, TargetCtx, SourceLibrary, TargetLibrary, SubFolder, newDSfolder, Sourcefields, Targetfields, listExcelFileInformation, docSetContentType);

                                        }

                                    }

                                    else

                                    {

                                        //TargetFolderURL

                                        var newFolder = TargetCtx.Web.Folders.Add(TargetFolderURL);

                                        TargetFolder.Context.Load(newFolder);

                                        TargetFolder.Context.Load(newFolder.ListItemAllFields);

                                        TargetFolder.Context.ExecuteQuery();

                                        try

                                        {

                                            var Author = TargetCtx.Web.EnsureUser(((FieldUserValue)SubFolder.ListItemAllFields["Author"]).Email);

                                            newFolder.ListItemAllFields["Author"] = Author;

                                            var Editor = TargetCtx.Web.EnsureUser(((FieldUserValue)SubFolder.ListItemAllFields["Editor"]).Email);

                                            newFolder.ListItemAllFields["Editor"] = Editor;

                                            newFolder.ListItemAllFields["Created"] = SubFolder.ListItemAllFields["Created"];

                                            newFolder.ListItemAllFields["Modified"] = SubFolder.ListItemAllFields["Modified"];

                                            newFolder.ListItemAllFields.Update();

                                            TargetFolder.Context.ExecuteQuery();

                                        }

                                        catch (Exception ex)

                                        {

                                            string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                                            Log.Instance.Warn(exString);

                                        }


                                        Console.WriteLine("Folder Added:" + SubFolder.Name);

                                        System.Threading.Thread.Sleep(200);


                                        #region audit excel information

                                        TargetCtx.Load(newFolder.ListItemAllFields);

                                        TargetCtx.ExecuteQuery();

                                        Common.ExcelFileInformation excelFileInformation = getExcelFileInformation(TargetCtx, newFolder.ListItemAllFields, TargetLibrary.Title);

                                        if (excelFileInformation != null)

                                        {

                                            listExcelFileInformation.Add(excelFileInformation);

                                        }

                                        #endregion


                                        CopyAllFilesWithMetadata(SourceCtx, TargetCtx, SourceLibrary, TargetLibrary, SubFolder, newFolder, Sourcefields, Targetfields, listExcelFileInformation, docSetContentType);

                                    }

                                }

                            }

                        }

                    }

                }

                Log.Instance.Info("Done! to Copy All Files With Metadata to target site successfully...");

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

        }


        #region Copy all Files of Folder to Document Set Using Buisness Rule Method

        public static void CopyAllFilesToDocumentSet(ClientContext SourceCtx, ClientContext TargetCtx, List SourceLibrary, List TargetLibrary, string SourceFolderRelativeUrl, string TargetFolderRelativeUrl, FieldCollection Sourcefields, FieldCollection Targetfields, DataTable FiledataSet, DataTable InsureddataSet, DataTable auditDtdocSet)

        {

            try

            {

                Folder SourceFolder = SourceCtx.Web.GetFolderByServerRelativeUrl(SourceFolderRelativeUrl);

                SourceCtx.Load(SourceFolder);

                SourceCtx.ExecuteQuery();


                Folder TargetFolder = TargetCtx.Web.GetFolderByServerRelativeUrl(TargetFolderRelativeUrl);

                TargetCtx.Load(TargetFolder);

                TargetCtx.ExecuteQuery();


                if (SourceFolder != null)

                {

                    CamlQuery camlQuery = new CamlQuery();

                    camlQuery.ViewXml = @"<View Scope='RecursiveAll'>

                                      <Query>

                                      </Query>

                                  </View>";

                    camlQuery.FolderServerRelativeUrl = SourceFolder.ServerRelativeUrl;

                    ListItemCollection listItems = SourceLibrary.GetItems(camlQuery);

                    SourceCtx.Load(listItems);

                    SourceCtx.ExecuteQuery();

                    foreach (var item in listItems)

                    {

                        if (item.FileSystemObjectType == FileSystemObjectType.File)

                        {

                        }

                        else if (item.FileSystemObjectType == FileSystemObjectType.Folder)

                        {

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

        }

        #endregion

        public static Microsoft.SharePoint.Client.Folder createNewDocumentSet(ClientContext clientContext, Folder SourceFolder, Folder TargetFolder, string TargetListName, string documentSetName)

        {

            Microsoft.SharePoint.Client.Folder folder = null;

            try

            {

                var Targetlist = clientContext.Web.Lists.GetByTitle(TargetListName);

                clientContext.Load(Targetlist, l => l.RootFolder, l => l.ContentTypes, l => l.Fields);

                clientContext.ExecuteQuery();


                string documentSetCTName = SourceFolder.ListItemAllFields.ContentType.Name;

                var dsct = Targetlist.GetContentTypeByName(documentSetCTName);

                if (dsct == null)

                {

                    dsct = clientContext.Web.GetContentTypeByName(documentSetCTName);

                }

                clientContext.Load(dsct);

                clientContext.ExecuteQuery();

                ContentTypeId dsctID = dsct.Id;


                //use the id of the list content type

                //var ct = list.ContentTypes.GetById("0x0120D52000A623EADA52BAF246AAD86D3E8816B2FE");

                //var ct = list.ContentTypes.GetById(dsctID);

                //clientContext.Load(ct);                       

                try

                {

                    //var itemInfo = new ListItemCreationInformation();

                    //itemInfo.UnderlyingObjectType = FileSystemObjectType.Folder;

                    //itemInfo.LeafName = documentSetName;

                    //itemInfo.FolderUrl = list.RootFolder.ServerRelativeUrl;

                    //var item = list.AddItem(itemInfo);

                    //item["ContentTypeId"] = "0x0120D520";

                    //item["HTML_x0020_File_x0020_Type"] = "SharePoint.DocumentSet";

                    //item.Update();




                    //DocumentSet.Create(clientContext, list.RootFolder, documentSetName, dsct.Id);

                    //clientContext.ExecuteQuery();

                    //Log.Instance.Info(string.Format("New Account '{0}' has created successfully...", documentSetName));

                    //folder = clientContext.Web.GetFolderByServerRelativeUrl(list.RootFolder.ServerRelativeUrl + "/" + documentSetName);

                    //clientContext.Load(folder, fd => fd.Files, fd => fd.ListItemAllFields, fd => fd.UniqueId);

                    //clientContext.ExecuteQuery();

                    //Dictionary<string, object> folderFieldValue = folder.ListItemAllFields.FieldValues;

                    //ListItem documentSetItem = folder.ListItemAllFields;

                    //await updateDocumentSet(clientContext, list, documentSetName);

                    //Log.Instance.Info(string.Format("Account '{0}' meta data has updated successfully...", documentSetName));


                    if (dsctID != null)

                    {

                        Folder documentsetFolder = TargetFolder.CreateDocumentSet(documentSetName, dsctID);

                        clientContext.Load(documentsetFolder, f => f.ListItemAllFields, f => f.ServerRelativeUrl);

                        clientContext.ExecuteQuery();


                        Log.Instance.Info(string.Format("New Account '{0}' has created successfully...", documentSetName));

                        folder = clientContext.Web.GetFolderByServerRelativeUrl(documentsetFolder.ServerRelativeUrl);

                        clientContext.Load(folder, fd => fd.ServerRelativeUrl, fd => fd.Files, fd => fd.ListItemAllFields, fd => fd.UniqueId);

                        clientContext.ExecuteQuery();

                    }

                }

                catch (Exception ex)

                {

                    string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                    Log.Instance.Error(exString);

                }

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

            return folder;

        }

        public static void updateDocumentSetMetaData(ClientContext SourceCtx, ClientContext TargetCtx, Folder DS_SourceFolder, Folder DS_TargetFolder, FieldCollection Sourcefields, FieldCollection Targetfields)

        {

            try

            {

                Folder DS_Sourcefolder = SourceCtx.Web.GetFolderByServerRelativeUrl(DS_SourceFolder.ServerRelativeUrl);

                SourceCtx.Load(DS_Sourcefolder, f => f.ListItemAllFields, f => f.Files, f => f.Files.Include(_f => _f.ListItemAllFields));

                SourceCtx.ExecuteQuery();


                Folder DS_Targetfolder = TargetCtx.Web.GetFolderByServerRelativeUrl(DS_TargetFolder.ServerRelativeUrl);

                TargetCtx.Load(DS_Targetfolder, dsf => dsf.Name, dsf => dsf.ListItemAllFields, dsf => dsf.Files, dsf => dsf.Files.Include(_dsf => _dsf.ListItemAllFields));

                TargetCtx.ExecuteQuery();


                ListItem DS_SourceItem = DS_Sourcefolder.ListItemAllFields;

                ListItem DS_TargetItem = DS_Targetfolder.ListItemAllFields;


                //Set Metadata values from the source                        

                Sourcefields.Cast<Field>().ToList().ForEach(sf =>

                {

                    string srcFieldName = sf.Title;

                    string srcFieldInternalName = sf.InternalName;

                    if (DS_SourceItem.FieldValues.ContainsKey(srcFieldInternalName))

                    {

                        if (DS_TargetItem.FieldValues.ContainsKey(srcFieldInternalName))

                        {

                            DS_TargetItem[srcFieldInternalName] = DS_SourceItem.FieldValues[srcFieldInternalName];

                        }

                    }

                });

                try

                {

                    var Author = TargetCtx.Web.EnsureUser(((FieldUserValue)DS_SourceItem["Author"]).Email);

                    DS_TargetItem["Author"] = Author;

                    var Editor = TargetCtx.Web.EnsureUser(((FieldUserValue)DS_SourceItem["Editor"]).Email);

                    DS_TargetItem["Editor"] = Editor;

                    DS_TargetItem["Created"] = DS_SourceItem["Created"];

                    DS_TargetItem["Modified"] = DS_SourceItem["Modified"];


                    DS_TargetItem.Update();

                    TargetCtx.ExecuteQuery();

                }

                catch (Exception ex)

                {

                    string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                    Log.Instance.Warn(exString);

                }

                Log.Instance.Info(string.Format("Account '{0}' meta data has updated successfully...", DS_Targetfolder.Name));

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

        }


        public static List<ListItem> GetAllFolder(ClientContext context, string ListName)

        {

            //List<ListItem> items = null;

            List SPList = null;

            //List <Folder> folders = new List<Folder>();

            List<ListItem> folders = new List<ListItem>();

            List<Common.FolderInformation> listFolderInformation = new List<Common.FolderInformation>();

            try

            {

                SPList = context.Web.Lists.GetByTitle(ListName);

                context.Load(SPList);

                context.ExecuteQuery();

                List<ListItemCollection> listItemCollection = Task.Run(() => csomListCommon.GetSharePointDataAsync(context, ListName)).GetAwaiter().GetResult();

                List<Task> taskList = new List<Task>();

                int left = Console.CursorLeft;

                int top = Console.CursorTop;

                listItemCollection.ForEach(listItems =>

                {

                    var foldercollection = listItems.Cast<ListItem>().Where(li => li.FileSystemObjectType == FileSystemObjectType.Folder).Select(li => li).ToList();

                    folders.AddRange(foldercollection);

                    Console.SetCursorPosition(left, top);

                    Console.WriteLine(string.Format("Folders Count: {0}", folders.Count.ToString()));

                });

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

            finally

            {

                int left = Console.CursorLeft;

                int top = Console.CursorTop;

                Type type = typeof(Common.FolderInformation);

                PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);


                System.Data.DataTable dtFolder = new System.Data.DataTable();

                dtFolder.TableName = type.Name;

                foreach (PropertyInfo prop in properties)

                {

                    //Setting column names as Property names  

                    dtFolder.Columns.Add(prop.Name);

                }

                foreach (var currListItem in folders)

                {

                    try

                    {

                        //context.Load(folder, f => f.Name, f => f.ListItemAllFields, f => f.ServerRelativeUrl);

                        //context.ExecuteQueryRetry();

                        //listfolder.Add(folder);


                        #region audit folder excel information                       

                        //var currListItem = folder.ListItemAllFields;

                        Common.FolderInformation excelFolderInformation = getFolderInformation(context, currListItem);

                        var values = new object[properties.Length];

                        for (int i = 0; i < properties.Length; i++)

                        {

                            values[i] = properties[i].GetValue(excelFolderInformation, null);

                        }

                        dtFolder.Rows.Add(values);

                        Console.SetCursorPosition(left, top);

                        Console.WriteLine(string.Format("Processing DataTable to add folder information. \n Folders Count: {0}", dtFolder.Rows.Count.ToString()));

                        #endregion

                    }

                    catch (Exception ex)

                    {

                        string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                        Log.Instance.Error(exString);

                    }

                }

                if (dtFolder != null)

                {

                    if (dtFolder.Rows.Count > 0)

                    {

                        Console.WriteLine("\n");

                        Log.Instance.Debug(string.Format("Done! to build DataTable with folder information. Total Folder information Count: {0}", dtFolder.Rows.Count.ToString()));

                        context.Load(SPList.Fields, fc => fc.Where(f => f.Hidden == false && f.ReadOnlyField == false && f.InternalName != "Attachments" && f.InternalName != "ContentType"));

                        context.ExecuteQuery();

                        string csvFilePath = @"C:\Exported Documents\Export Folders\" + "" + string.Format("{0}_{1}.csv", SPList.Title, "Folders_" + DateTime.Now.ToString("MM-dd-yyyy hh-mm"));

                        Log.Instance.Debug(string.Format("start to get all folders information to csv files as given path. \n CSV File Path: {0}", csvFilePath));

                        try

                        {

                            //System.Data.DataTable dt = MakeDataTable.ToProcessDataTable<Common.ExcelFileInformation>(listExcelFileInformation, SPList.Fields);

                            Log.Instance.Debug(string.Format("Processing to build csv file. Please wait..."));

                            ExcelManager.ToCSV(dtFolder, csvFilePath);

                            Log.Instance.Info(string.Format("Done! to load all folders information to csv files as given path. \n CSV File Path: {0}", csvFilePath));

                        }

                        catch (Exception ex)

                        {

                            string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                            Log.Instance.Error(exString);

                        }

                    }

                }

            }

            return folders;

        }


        public static List<OSP.ListItem> GetAllFiles(ClientContext context, string ListName)

        {

            //List<OSP.File> oFiles = new List<OSP.File>();

            List SPList = null;

            //List <Folder> folders = new List<Folder>();

            List<ListItem> oFiles = new List<ListItem>();

            //List<Common.FolderInformation> listFolderInformation = new List<Common.FolderInformation>();

            try

            {

                SPList = context.Web.Lists.GetByTitle(ListName);

                context.Load(SPList);

                context.Load(SPList.Fields, fc => fc.Where(f => f.Hidden == false && f.ReadOnlyField == false && f.InternalName != "Attachments" && f.InternalName != "ContentType"));

                context.ExecuteQuery();

                List<ListItemCollection> listItemCollection = Task.Run(() => csomListCommon.GetSharePointDataAsync(context, ListName)).GetAwaiter().GetResult();

                int left = Console.CursorLeft;

                int top = Console.CursorTop;

                //int result = 0;

                listItemCollection.ForEach(listItems =>

                {

                    var filecollection = listItems.Cast<ListItem>().Where(li => li.FileSystemObjectType == FileSystemObjectType.File).Select(li => li).ToList();

                    oFiles.AddRange(filecollection);

                    Console.SetCursorPosition(left, top);

                    Console.WriteLine(string.Format("Files Count: {0}", oFiles.Count.ToString()));

                });

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

            finally

            {

                var fieldCollection = SPList.Fields;

                System.Data.DataTable dtFiles = new System.Data.DataTable();

                if (oFiles != null)

                {

                    if (oFiles.Count > 0)

                    {

                        dtFiles = ExportDataTable(fieldCollection, oFiles);

                    }

                }

                if (dtFiles != null)

                {

                    if (dtFiles.Rows.Count > 0)

                    {

                        Console.WriteLine("\n");

                        Log.Instance.Debug(string.Format("Total File information Count: {0}", dtFiles.Rows.Count.ToString()));

                        string csvFilePath = @"C:\Exported Documents\Export Files Information\" + "" + string.Format("{0}_{1}.csv", SPList.Title, "Files_" + DateTime.Now.ToString("MM-dd-yyyy hh-mm"));

                        //Log.Instance.Debug(string.Format("start to get all folders information to csv files as given path. \n CSV File Path: {0}", csvFilePath));

                        try

                        {

                            //System.Data.DataTable dt = MakeDataTable.ToProcessDataTable<Common.ExcelFileInformation>(listExcelFileInformation, SPList.Fields);

                            Log.Instance.Debug(string.Format("Processing to build csv file. Please wait..."));

                            ExcelManager.ToCSV(dtFiles, csvFilePath);

                            Log.Instance.Info(string.Format("All File information added to csv file as given below.\n CSV File Path: {0}", csvFilePath));                            

                        }

                        catch (Exception ex)

                        {

                            string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                            Log.Instance.Error(exString);

                        }

                    }

                }

            }

            return oFiles;

        }


        public static List<Microsoft.SharePoint.Client.ListItem> GetDocumentSetsInfo(ClientContext ctx, string docLibraryName, string docSetContentTypeName)

        {


            List<Microsoft.SharePoint.Client.ListItem> docSetFolders = null;

            Microsoft.SharePoint.Client.List list = null;

            try

            {

                list = ctx.Web.Lists.GetByTitle(docLibraryName);

                ctx.Load(list);

                ctx.Load(list.Fields, fc => fc.Where(f => f.Hidden == false && f.ReadOnlyField == false && f.InternalName != "Attachments" && f.InternalName != "ContentType"));

                ctx.ExecuteQuery();

                List<ListItemCollection> listItemCollection = null;

                try

                {

                    listItemCollection = Task.Run(() => csomListCommon.GetSharePointDataAsync(ctx, docLibraryName)).GetAwaiter().GetResult();

                }

                catch (Exception ex)

                {

                    string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                    Log.Instance.Error(exString);

                }

                

                List<Task> taskList = new List<Task>();

                int left = Console.CursorLeft;

                int top = Console.CursorTop;

                docSetFolders = new List<Microsoft.SharePoint.Client.ListItem>();

                //int resultset=0;

                //listItemCollection.ForEach(listItems =>

                //{

                //    //taskList = new List<Task>();

                //    ctx.Load(listItems, li => li.Include(it => it, it => it.ContentType, it => it.FileSystemObjectType, it => it.Folder, it => it.Folder.ListItemAllFields));

                //    Task.Run(async () => await ctx.ExecuteQueryAsync()).GetAwaiter().GetResult();

                //    resultset+=listItems.Count;

                //    Console.SetCursorPosition(left, top);

                //    Console.WriteLine(string.Format("Resultset Count: {0}", resultset.ToString()));

                //});                

                listItemCollection.ForEach(listItems =>

                {

                    var foldercollection = listItems.Cast<ListItem>().Where(li => li.FileSystemObjectType == FileSystemObjectType.Folder).Select(li => li).ToList();

                    docSetFolders.AddRange(foldercollection);

                    Console.SetCursorPosition(left, top);

                    Console.WriteLine(string.Format("DocumentSet Count: {0}", docSetFolders.Count.ToString()));

                });

                Log.Instance.Debug(string.Format("Folders Count: {0}", docSetFolders.Count.ToString()));

                ctx.Dispose();

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

            finally

            {

                Common.DocumentSetInformation documentSetInformation = new Common.DocumentSetInformation();

                int left = Console.CursorLeft;

                int top = Console.CursorTop;

                Type type = typeof(Common.DocumentSetInformation);

                PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);


                System.Data.DataTable dtdocSet = new System.Data.DataTable();

                dtdocSet.TableName = type.Name;

                foreach (PropertyInfo prop in properties)

                {

                    //Setting column names as Property names  

                    dtdocSet.Columns.Add(prop.Name);

                }

                foreach (ListItem currListItem in docSetFolders)

                {

                    try

                    {

                        //context.Load(folder, f => f.Name, f => f.ListItemAllFields, f => f.ServerRelativeUrl);

                        //context.ExecuteQueryRetry();

                        //listfolder.Add(folder);


                        #region audit folder excel information                       

                        //var currListItem = folder.ListItemAllFields;

                        Common.DocumentSetInformation excelFolderInformation = getdocumentSetInformation(ctx, currListItem, docLibraryName);

                        var values = new object[properties.Length];

                        for (int i = 0; i < properties.Length; i++)

                        {

                            values[i] = properties[i].GetValue(excelFolderInformation, null);

                        }

                        dtdocSet.Rows.Add(values);

                        Console.SetCursorPosition(left, top);

                        Console.WriteLine(string.Format("Total Documentset Folder Count: {0}", dtdocSet.Rows.Count.ToString()));

                        #endregion

                    }

                    catch (Exception ex)

                    {

                        string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                        Log.Instance.Error(exString);

                    }

                }

                if (dtdocSet != null)

                {

                    if (dtdocSet.Rows.Count > 0)

                    {

                        Console.WriteLine("\n");

                        //Log.Instance.Debug(string.Format("Done! to build DataTable with folder information. Total Folder information Count: {0}", dtdocSet.Rows.Count.ToString()));

                        //ctx.Load(list.Fields, fc => fc.Where(f => f.Hidden == false && f.ReadOnlyField == false && f.InternalName != "Attachments" && f.InternalName != "ContentType"));

                        //ctx.ExecuteQuery();

                        string csvFilePath = @"C:\Exported Documents\Export DocumentSets\" + "" + string.Format("{0}_{1}.csv", list.Title, "DSet_" + DateTime.Now.ToString("MM-dd-yyyy hh-mm"));

                        //Log.Instance.Trace(string.Format("start to get all Documentset information to csv files as given path. \n CSV File Path: {0}", csvFilePath));

                        try

                        {

                            //System.Data.DataTable dt = MakeDataTable.ToProcessDataTable<Common.ExcelFileInformation>(listExcelFileInformation, SPList.Fields);

                            Log.Instance.Debug(string.Format("Processing to build csv file. Please wait..."));

                            ExcelManager.ToCSV(dtdocSet, csvFilePath);

                            Log.Instance.Info(string.Format("Documentset information added to csv file as given below. \n CSV File Path: {0}", csvFilePath));

                        }

                        catch (Exception ex)

                        {

                            string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                            Log.Instance.Error(exString);

                        }

                    }

                }

            }

            return docSetFolders;

        }


        public static List<Folder> GetAllFolder(ClientContext context, List SPList)

        {

            //List<ListItem> items = null;

            List<Folder> folders = new List<Folder>();

            List<Common.FolderInformation> listFolderInformation = new List<Common.FolderInformation>();

            try

            {

                int rowLimit = int.Parse(Appsetting.rowLimits);

                var camlQuery = new CamlQuery();

                //string queryOnlyforFiles = string.Format(CAML.Where(CAML.Eq(CAML.FieldValue("FSObjType", "Integer", "{0}"))), 1);

                string queryOnlyforFiles = string.Empty;

                string viewxml = CAML.ViewQuery(ViewScope.RecursiveAll, queryOnlyforFiles, CAML.OrderBy(new OrderByField("ID", false)), rowLimit: rowLimit);


                camlQuery.ViewXml = viewxml;

                int left = Console.CursorLeft;

                int top = Console.CursorTop;

                //items = new List<ListItem>();                

                int resultSize = 0;

                ListItemCollectionPosition position = null;

                do

                {

                    ListItemCollection listItems = null;

                    camlQuery.ListItemCollectionPosition = position;

                    listItems = SPList.GetItems(camlQuery);

                    context.Load(listItems);

                    context.ExecuteQueryRetry();

                    context.Load(listItems, li => li.Include(it => it.ContentType,

                                                                 it => it.FileSystemObjectType,

                                                                 it => it.Folder,

                                                                 it => it.Folder.ServerRelativeUrl,

                                                                 it => it.Folder.Name,

                                                                 it => it.Folder.ListItemAllFields,

                                                                 it => it.Folder.ListItemAllFields.ContentType));

                    context.ExecuteQueryRetry();

                    var foldercollection = listItems.Cast<ListItem>().Where(li => li.FileSystemObjectType == FileSystemObjectType.Folder).Select(li => li.Folder).ToList();

                    position = listItems.ListItemCollectionPosition;

                    //items.AddRange(listItems.ToList());

                    resultSize = resultSize + listItems.Count();

                    folders.AddRange(foldercollection);

                    Console.SetCursorPosition(left, top);

                    Console.WriteLine(string.Format("Folders Count: {0}", folders.Count.ToString()));

                    Console.WriteLine(string.Format("Item Count: {0}", resultSize.ToString()));

                    if (folders.Count() > 1500)

                    {

                        position = null;

                    }

                }

                while (position != null);

                Log.Instance.Debug(string.Format("Folders Count: {0}", folders.Count.ToString()));

                Log.Instance.Debug(string.Format("Item Count: {0}", resultSize.ToString()));

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

            finally

            {

                int left = Console.CursorLeft;

                int top = Console.CursorTop;

                Type type = typeof(Common.FolderInformation);

                PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);


                System.Data.DataTable dtFolder = new System.Data.DataTable();

                dtFolder.TableName = type.Name;

                foreach (PropertyInfo prop in properties)

                {

                    //Setting column names as Property names  

                    dtFolder.Columns.Add(prop.Name);

                }

                foreach (Folder folder in folders)

                {

                    try

                    {

                        //context.Load(folder, f => f.Name, f => f.ListItemAllFields, f => f.ServerRelativeUrl);

                        //context.ExecuteQueryRetry();

                        //listfolder.Add(folder);


                        #region audit folder excel information                       

                        var currListItem = folder.ListItemAllFields;

                        Common.FolderInformation excelFolderInformation = getFolderInformation(context, currListItem);

                        var values = new object[properties.Length];

                        for (int i = 0; i < properties.Length; i++)

                        {

                            values[i] = properties[i].GetValue(excelFolderInformation, null);

                        }

                        dtFolder.Rows.Add(values);

                        Console.SetCursorPosition(left, top);

                        Console.WriteLine(string.Format("Processing DataTable to add folder information. \n Folders Count: {0}", dtFolder.Rows.Count.ToString()));

                        #endregion

                    }

                    catch (Exception ex)

                    {

                        string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                        Log.Instance.Error(exString);

                    }

                }

                if (dtFolder != null)

                {

                    if (dtFolder.Rows.Count > 0)

                    {

                        Console.WriteLine("\n");

                        Log.Instance.Debug(string.Format("Done! to build DataTable with folder information. Total Folder information Count: {0}", dtFolder.Rows.Count.ToString()));

                        context.Load(SPList.Fields, fc => fc.Where(f => f.Hidden == false && f.ReadOnlyField == false && f.InternalName != "Attachments" && f.InternalName != "ContentType"));

                        context.ExecuteQuery();

                        string csvFilePath = @"C:\Exported Documents\Export Folders\" + "" + string.Format("{0}_{1}.csv", SPList.Title, "Folders_" + DateTime.Now.ToString("MM-dd-yyyy hh-mm"));

                        Log.Instance.Debug(string.Format("start to get all folders information to csv files as given path. \n CSV File Path: {0}", csvFilePath));

                        try

                        {

                            //System.Data.DataTable dt = MakeDataTable.ToProcessDataTable<Common.ExcelFileInformation>(listExcelFileInformation, SPList.Fields);

                            Log.Instance.Debug(string.Format("Processing to build csv file. Please wait..."));

                            ExcelManager.ToCSV(dtFolder, csvFilePath);

                            Log.Instance.Info(string.Format("Done! to load all folders information to csv files as given path. \n CSV File Path: {0}", csvFilePath));

                        }

                        catch (Exception ex)

                        {

                            string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                            Log.Instance.Error(exString);

                        }

                    }

                }

            }

            return folders;

        }


        public static List<OSP.File> GetAllFiles(ClientContext context, List SPList)

        {

            List<OSP.File> oFiles = new List<OSP.File>();

            try

            {

                int rowLimit = int.Parse(Appsetting.rowLimits);

                context.Load(SPList.Fields, fc => fc.Where(f => f.Hidden == false && f.ReadOnlyField == false && f.InternalName != "Attachments" && f.InternalName != "ContentType"));

                context.ExecuteQuery();

                var camlQuery = new CamlQuery();

                //string queryOnlyforFiles = string.Format(CAML.Where(CAML.Eq(CAML.FieldValue("FSObjType", "Integer", "{0}"))), 1);

                string queryOnlyforFiles = string.Empty;

                string viewxml = CAML.ViewQuery(ViewScope.RecursiveAll, queryOnlyforFiles, CAML.OrderBy(new OrderByField("ID", false)), rowLimit: rowLimit);


                camlQuery.ViewXml = viewxml;

                int left = Console.CursorLeft;

                int top = Console.CursorTop;

                //items = new List<ListItem>();                

                int resultSize = 0;

                ListItemCollectionPosition position = null;

                do

                {

                    ListItemCollection listItems = null;

                    camlQuery.ListItemCollectionPosition = position;

                    listItems = SPList.GetItems(camlQuery);

                    context.Load(listItems);

                    Task.Run(() => context.ExecuteQueryAsync()).GetAwaiter().GetResult();

                    context.Load(listItems, li => li.Include(it => it.ContentType,

                                                                   it => it.FileSystemObjectType,

                                                                   it => it.File,

                                                                   it => it.File.ServerRelativeUrl,

                                                                   it => it.File.Name,

                                                                   it => it.File.ListItemAllFields,

                                                                   it => it.File.ListItemAllFields.ContentType));

                    Task.Run(() => context.ExecuteQueryRetryAsync()).GetAwaiter().GetResult();


                    var filecollection = listItems.Cast<ListItem>().Where(li => li.FileSystemObjectType == FileSystemObjectType.File).Select(li => li.File).ToList();

                    position = listItems.ListItemCollectionPosition;

                    //items.AddRange(listItems.ToList());

                    resultSize = resultSize + listItems.Count();

                    oFiles.AddRange(filecollection);

                    Console.SetCursorPosition(left, top);

                    Console.WriteLine(string.Format("Files Count: {0}", oFiles.Count.ToString()));

                    Console.WriteLine(string.Format("Item Count: {0}", resultSize.ToString()));

                    if (oFiles.Count() > 1500)

                    {

                        position = null;

                    }

                }

                while (position != null);

                Log.Instance.Debug(string.Format("Files Count: {0}", oFiles.Count.ToString()));

                Log.Instance.Debug(string.Format("Item Count: {0}", resultSize.ToString()));

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

            finally

            {

                var fieldCollection = SPList.Fields;

                System.Data.DataTable dtFiles = new System.Data.DataTable();

                //dtFiles = MakeDataTable.FileInformationToDataTable(oFiles, fieldCollection, SPList.Title);

                dtFiles = MakeDataTable.FileNoMetaDataToDataTable(oFiles, fieldCollection, SPList.Title);

                if (dtFiles != null)

                {

                    if (dtFiles.Rows.Count > 0)

                    {

                        Console.WriteLine("\n");

                        Log.Instance.Debug(string.Format("Done! to build DataTable with File information. Total File information Count: {0}", dtFiles.Rows.Count.ToString()));

                        string csvFilePath = @"C:\Exported Documents\Export Files Information\" + "" + string.Format("{0}_{1}.csv", SPList.Title, "Files_" + DateTime.Now.ToString("MM-dd-yyyy hh-mm"));

                        Log.Instance.Debug(string.Format("start to get all folders information to csv files as given path. \n CSV File Path: {0}", csvFilePath));

                        try

                        {

                            //System.Data.DataTable dt = MakeDataTable.ToProcessDataTable<Common.ExcelFileInformation>(listExcelFileInformation, SPList.Fields);

                            Log.Instance.Debug(string.Format("Processing to build csv file. Please wait..."));

                            ExcelManager.ToCSV(dtFiles, csvFilePath);

                            Log.Instance.Info(string.Format("Done! to load all File information to csv files as given below. \n CSV File Path: {0}", csvFilePath));

                        }

                        catch (Exception ex)

                        {

                            string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                            Log.Instance.Error(exString);

                        }

                    }

                }

            }

            return oFiles;

        }


        public static List<Microsoft.SharePoint.Client.Folder> GetAllDocumentSet(ClientContext ctx, string docLibraryName, string docSetContentTypeName)

        {

            List<Microsoft.SharePoint.Client.Folder> docSetFolders = null;

            Microsoft.SharePoint.Client.List list = null;

            try

            {

                list = ctx.Web.Lists.GetByTitle(docLibraryName);

                ctx.Load(list);

                ctx.ExecuteQuery();

                int limit = int.Parse(Appsetting.rowLimits);

                var query = new CamlQuery()

                {

                    //ViewXml = string.Format(CAML.ViewQuery(ViewScope.RecursiveAll, CAML.Where(CAML.Eq(CAML.FieldValue("ContentType", "Computed", "{0}"))), CAML.OrderBy(new OrderByField("ID", false)), rowLimit: limit), docSetContentTypeName)

                    ViewXml = string.Format(CAML.ViewQuery(ViewScope.RecursiveAll, String.Empty, CAML.OrderBy(new OrderByField("ID", false)), rowLimit: limit))

                    //ViewXml = String.Format("<View><Query><Where><Eq><FieldRef Name='ContentType' /><Value Type='Computed'>Document Set</Value></Eq></Where></Query></View>")

                };

                int resultSize = 0;

                int left = Console.CursorLeft;

                int top = Console.CursorTop;

                docSetFolders = new List<Microsoft.SharePoint.Client.Folder>();

                ListItemCollectionPosition position = null;


                do

                {

                    List<Task> listItemstasks = new List<Task>();

                    List<Task> tasks = new List<Task>();

                    ListItemCollection listItems = null;

                    query.ListItemCollectionPosition = position;

                    listItems = list.GetItems(query);

                    ctx.Load(listItems);

                    listItemstasks.Add(ctx.ExecuteQueryAsync());

                    Task.WhenAll(listItemstasks).Wait();

                    position = listItems.ListItemCollectionPosition;

                    //items.AddRange(listItems.ToList());

                    //var collection = Partition<ListItemCollection>(ListItemCollection, 5);                    

                    ctx.Load(listItems, li => li.Include(it => it.ContentType,

                                                                it => it.FileSystemObjectType,

                                                                it => it.Folder,

                                                                it => it.Folder.ServerRelativeUrl,

                                                                it => it.Folder.Name,

                                                                it => it.Folder.ListItemAllFields,

                                                                it => it.Folder.ListItemAllFields.FieldValuesAsText,

                                                                it => it.Folder.ListItemAllFields.File,

                                                                it => it.Folder.ListItemAllFields.ContentType));

                    tasks.Add(ctx.ExecuteQueryRetryAsync());

                    Task.WhenAll(tasks).Wait();

                    resultSize = resultSize + listItems.Count();

                    var folderCollection = listItems.Cast<ListItem>().Where(li => li.FileSystemObjectType == FileSystemObjectType.Folder && li.ContentType.Name == docSetContentTypeName).Select(li => li.Folder).ToList();

                    docSetFolders.AddRange(folderCollection);

                    Console.SetCursorPosition(left, top);

                    Console.WriteLine(string.Format("DocumentSet Count: {0}", docSetFolders.Count.ToString()));

                    Console.WriteLine(string.Format("Total List Items Counts : {0}", resultSize.ToString()));

                    //if (docSetFolders.Count() > 1500)

                    //{

                    //    position = null;

                    //}

                }

                while (position != null);

                Log.Instance.Debug(string.Format("Folders Count: {0}", docSetFolders.Count.ToString()));

                Log.Instance.Debug(string.Format("Total List Items Counts : {0}", resultSize.ToString()));

                ctx.Dispose();

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

            finally

            {

                Common.DocumentSetInformation documentSetInformation = new Common.DocumentSetInformation();

                int left = Console.CursorLeft;

                int top = Console.CursorTop;

                Type type = typeof(Common.DocumentSetInformation);

                PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);


                System.Data.DataTable dtdocSet = new System.Data.DataTable();

                dtdocSet.TableName = type.Name;

                foreach (PropertyInfo prop in properties)

                {

                    //Setting column names as Property names  

                    dtdocSet.Columns.Add(prop.Name);

                }

                foreach (Folder folder in docSetFolders)

                {

                    try

                    {

                        //context.Load(folder, f => f.Name, f => f.ListItemAllFields, f => f.ServerRelativeUrl);

                        //context.ExecuteQueryRetry();

                        //listfolder.Add(folder);


                        #region audit folder excel information                       

                        var currListItem = folder.ListItemAllFields;

                        Common.DocumentSetInformation excelFolderInformation = getdocumentSetInformation(ctx, currListItem, docLibraryName);

                        var values = new object[properties.Length];

                        for (int i = 0; i < properties.Length; i++)

                        {

                            values[i] = properties[i].GetValue(excelFolderInformation, null);

                        }

                        if (dtdocSet.Rows.Count == 12346)

                        {

                            Console.WriteLine("Please check error..");

                        }

                        dtdocSet.Rows.Add(values);

                        Console.SetCursorPosition(left, top);

                        Console.WriteLine(string.Format("Processing DataTable to add Documentset information.\n Documentset Count: {0}", dtdocSet.Rows.Count.ToString()));

                        #endregion

                    }

                    catch (Exception ex)

                    {

                        string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                        Log.Instance.Error(exString);

                    }

                }

                if (dtdocSet != null)

                {

                    if (dtdocSet.Rows.Count > 0)

                    {

                        Console.WriteLine("\n");

                        //Log.Instance.Debug(string.Format("Done! to build DataTable with folder information. Total Folder information Count: {0}", dtdocSet.Rows.Count.ToString()));

                        //ctx.Load(list.Fields, fc => fc.Where(f => f.Hidden == false && f.ReadOnlyField == false && f.InternalName != "Attachments" && f.InternalName != "ContentType"));

                        //ctx.ExecuteQuery();

                        string csvFilePath = @"C:\Exported Documents\Export Files Information\" + "" + string.Format("{0}_{1}.csv", list.Title, "DSet_" + DateTime.Now.ToString("MM-dd-yyyy hh-mm"));

                        Log.Instance.Trace(string.Format("start to get all Documentset information to csv files as given path. \n CSV File Path: {0}", csvFilePath));

                        try

                        {

                            //System.Data.DataTable dt = MakeDataTable.ToProcessDataTable<Common.ExcelFileInformation>(listExcelFileInformation, SPList.Fields);

                            Log.Instance.Debug(string.Format("Processing to build csv file. Please wait..."));

                            ExcelManager.ToCSV(dtdocSet, csvFilePath);

                            Log.Instance.Info(string.Format("Done! to load all Documentset information to csv files as given path. \n CSV File Path: {0}", csvFilePath));

                        }

                        catch (Exception ex)

                        {

                            string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                            Log.Instance.Error(exString);

                        }

                    }

                }

            }

            return docSetFolders;

        }

        public static Common.ExcelFileInformation getExcelFileInformation(ClientContext ctx, ListItem lstItem, string listname)

        {

            Common.ExcelFileInformation fileInfo = new Common.ExcelFileInformation();

            ctx.Load(lstItem.ContentType);

            ctx.ExecuteQuery();

            var contetTypeId = lstItem.ContentType.Id;

            var currcontetTypeName = lstItem.ContentType.Name;

            #region call when ListItem type is File

            if (lstItem.FileSystemObjectType == FileSystemObjectType.File)

            {

                //ctx.Load(lstItem.File, f => f.Level, f => f.SiteId, f => f.WebId, f => f.ListId,

                //                                          f => f.ListItemAllFields, f => f.Name, f => f.ServerRelativeUrl,

                //                                          f => f.Author, f => f.CheckedOutByUser,

                //                                          f => f.ModifiedBy, f => f.TimeLastModified, f => f.Title,

                //                                          f => f.UniqueId, f => f.Versions);

                //// This is a File

                ////item.File.ListItemAllFields

                //ctx.ExecuteQuery();

                fileInfo.ListName = listname;

                fileInfo.Title = Convert.ToString(lstItem.FieldValues["Title"]);

                fileInfo.FileIDinList = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.ID]);

                fileInfo.LastModified = Convert.ToDateTime(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.LastModified]).ToShortDateString();

                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.LibraryCommonField.CheckoutUser))

                {

                    var checkoutuser = ((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.CheckoutUser]);

                    if (checkoutuser != null)

                        fileInfo.CheckedOutByUser = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.CheckoutUser]).LookupValue);

                }

                //if (lstItem.File.Versions != null)

                //    fileInfo.VersionsCount = Convert.ToString(lstItem.File.Versions.Count());


                fileInfo.FileName = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileLeafRef]);

                fileInfo.FSObJType = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FSObjType]);

                fileInfo.FileID = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.UniqueId]);

                fileInfo.FileType = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileType]);

                fileInfo.RelativeURL = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileRef]);

                fileInfo.FileDirPath = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileDirRef]);


                fileInfo.CreatedBy = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.CreatedBy]).LookupValue);

                fileInfo.CreatedByEmail = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.CreatedBy]).Email);

                fileInfo.CreatedTime = ((DateTime)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.Created]).ToString("MM/dd/yyyy");

                fileInfo.ModifiedTime = ((DateTime)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.Modified]).ToString("MM/dd/yyyy");

                fileInfo.ModifiedBy = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.ModifiedBy]).LookupValue);

                fileInfo.ModifiedByEmail = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.ModifiedBy]).Email);

                fileInfo.FileSize_KB = Convert.ToString(Math.Round((Convert.ToDouble(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileSize]) / 1024), 2)); //File size in KB  

                fileInfo.HtmlFileType = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.HTMLFileType]);

                fileInfo.ItemChildCount = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.ItemChildCount]);

                fileInfo.FolderChildCount = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FolderChildCount]);

                fileInfo.ContentType = currcontetTypeName;

                fileInfo.FileListItem = lstItem;

            }

            else if (lstItem.FileSystemObjectType == FileSystemObjectType.Folder)

            {

                fileInfo.FileIDinList = Convert.ToString(lstItem[CommonSiteCloumn.LibraryCommonField.ID]);

                fileInfo.FileName = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileLeafRef]);

                fileInfo.FSObJType = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FSObjType]);

                fileInfo.FileID = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.UniqueId]);

                fileInfo.FileType = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileType]);

                fileInfo.RelativeURL = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileRef]);

                fileInfo.FileDirPath = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileDirRef]);


                fileInfo.CreatedBy = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.CreatedBy]).LookupValue);

                fileInfo.CreatedByEmail = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.CreatedBy]).Email);

                fileInfo.CreatedTime = ((DateTime)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.Created]).ToString("MM/dd/yyyy");

                fileInfo.ModifiedTime = ((DateTime)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.Modified]).ToString("MM/dd/yyyy");

                fileInfo.ModifiedBy = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.ModifiedBy]).LookupValue);

                //fileInfo.ModifiedByEmail = lstItem.File.ModifiedBy.Email;

                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.LibraryCommonField.SMTotalFileStreamSize) && Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.SMTotalFileStreamSize]) != "")

                    fileInfo.FileSize_KB = Convert.ToString(Math.Round((Convert.ToDouble(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.SMTotalFileStreamSize]) / 1024), 2)); //File size in KB  

                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.LibraryCommonField.HTMLFileType))

                    fileInfo.HtmlFileType = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.HTMLFileType]);

                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.LibraryCommonField.ItemChildCount))

                    fileInfo.ItemChildCount = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.ItemChildCount]);

                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.LibraryCommonField.FolderChildCount))

                    fileInfo.FolderChildCount = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FolderChildCount]);

                fileInfo.ContentType = currcontetTypeName;

                fileInfo.FileListItem = lstItem;

            }

            #endregion

            return fileInfo;

        }

        public static Common.ExcelFileInformation getExcelFileInformation(ListItem lstItem, string ListName)

        {

            Common.ExcelFileInformation fileInfo = new Common.ExcelFileInformation();

            //ctx.Load(lstItem.ContentType);

            //ctx.ExecuteQuery();

            //var contetTypeId = lstItem.ContentType.Id;

            //var currcontetTypeName = lstItem.ContentType.Name;

            #region call when ListItem type is File

            if (lstItem.FileSystemObjectType == FileSystemObjectType.File)

            {

                fileInfo.ListName = ListName;

                fileInfo.Title = Convert.ToString(lstItem.FieldValues["Title"]);

                fileInfo.FileIDinList = Convert.ToString(lstItem.FieldValues["ID"]);

                fileInfo.LastModified = Convert.ToDateTime(lstItem.FieldValues["Last_x0020_Modified"]).ToShortDateString();

                fileInfo.FileName = Convert.ToString(lstItem.FieldValues["FileLeafRef"]);

                fileInfo.FSObJType = Convert.ToString(lstItem.FieldValues["FSObjType"]);

                fileInfo.FileID = Convert.ToString(lstItem.FieldValues["UniqueId"]);

                fileInfo.FileType = Convert.ToString(lstItem.FieldValues["File_x0020_Type"]);

                fileInfo.RelativeURL = Convert.ToString(lstItem.FieldValues["FileRef"]);

                fileInfo.FileDirPath = Convert.ToString(lstItem.FieldValues["FileDirRef"]);


                fileInfo.CreatedBy = Convert.ToString(((FieldUserValue)lstItem.FieldValues["Author"]).LookupValue);

                fileInfo.CreatedByEmail = Convert.ToString(((FieldUserValue)lstItem.FieldValues["Author"]).Email);

                fileInfo.CreatedTime = ((DateTime)lstItem.FieldValues["Created"]).ToString("MM/dd/yyyy");

                fileInfo.ModifiedTime = ((DateTime)lstItem.FieldValues["Modified"]).ToString("MM/dd/yyyy");

                fileInfo.ModifiedBy = Convert.ToString(((FieldUserValue)lstItem.FieldValues["Editor"]).LookupValue);

                fileInfo.ModifiedByEmail = Convert.ToString(((FieldUserValue)lstItem.FieldValues["Editor"]).Email);

                fileInfo.FileSize_KB = Convert.ToString(Math.Round((Convert.ToDouble(lstItem.FieldValues["File_x0020_Size"]) / 1024), 2)); //File size in KB  

                fileInfo.HtmlFileType = Convert.ToString(lstItem.FieldValues["HTML_x0020_File_x0020_Type"]);

                fileInfo.ItemChildCount = Convert.ToString(lstItem.FieldValues["ItemChildCount"]);

                fileInfo.FolderChildCount = Convert.ToString(lstItem.FieldValues["FolderChildCount"]);

                //fileInfo.ContentType = currcontetTypeName;

                fileInfo.FileListItem = lstItem;


            }

            else if (lstItem.FileSystemObjectType == FileSystemObjectType.Folder)

            {

                fileInfo.FileIDinList = Convert.ToString(lstItem.Id);

                fileInfo.FileName = Convert.ToString(lstItem.FieldValues["FileLeafRef"]);

                fileInfo.FSObJType = Convert.ToString(lstItem.FieldValues["FSObjType"]);

                fileInfo.FileID = Convert.ToString(lstItem.FieldValues["UniqueId"]);

                fileInfo.FileType = Convert.ToString(lstItem.FieldValues["File_x0020_Type"]);

                fileInfo.RelativeURL = Convert.ToString(lstItem.FieldValues["FileRef"]);

                fileInfo.FileDirPath = Convert.ToString(lstItem.FieldValues["FileDirRef"]);


                fileInfo.CreatedBy = Convert.ToString(((FieldUserValue)lstItem.FieldValues["Author"]).LookupValue);

                fileInfo.CreatedByEmail = Convert.ToString(((FieldUserValue)lstItem.FieldValues["Author"]).Email);

                fileInfo.CreatedTime = ((DateTime)lstItem.FieldValues["Created"]).ToString("MM/dd/yyyy");

                fileInfo.ModifiedTime = ((DateTime)lstItem.FieldValues["Modified"]).ToString("MM/dd/yyyy");

                fileInfo.ModifiedBy = Convert.ToString(((FieldUserValue)lstItem.FieldValues["Editor"]).LookupValue);

                //fileInfo.ModifiedByEmail = lstItem.File.ModifiedBy.Email;

                if (lstItem.FieldValues.ContainsKey("File_x0020_Size") && Convert.ToString(lstItem.FieldValues["File_x0020_Size"]) != "")

                    fileInfo.FileSize_KB = Convert.ToString(Math.Round((Convert.ToDouble(lstItem.FieldValues["File_x0020_Size"]) / 1024), 2)); //File size in KB  

                if (lstItem.FieldValues.ContainsKey("HTML_x0020_File_x0020_Type"))

                    fileInfo.HtmlFileType = Convert.ToString(lstItem.FieldValues["HTML_x0020_File_x0020_Type"]);

                if (lstItem.FieldValues.ContainsKey("ItemChildCount"))

                    fileInfo.ItemChildCount = Convert.ToString(lstItem.FieldValues["ItemChildCount"]);

                if (lstItem.FieldValues.ContainsKey("FolderChildCount"))

                    fileInfo.FolderChildCount = Convert.ToString(lstItem.FieldValues["FolderChildCount"]);

                fileInfo.FileListItem = lstItem;

            }

            #endregion

            return fileInfo;

        }


        public static Common.FileInformation getFileInformation(ListItem lstItem, string ListName)

        {

            Common.FileInformation fileInfo = new Common.FileInformation();

            //ctx.Load(lstItem.ContentType);

            //ctx.ExecuteQuery();

            //var contetTypeId = lstItem.ContentType.Id;

            //var currcontetTypeName = lstItem.ContentType.Name;

            #region call when ListItem type is File

            if (lstItem.FileSystemObjectType == FileSystemObjectType.File)

            {

                fileInfo.ListName = ListName;

                fileInfo.Title = Convert.ToString(lstItem.FieldValues["Title"]);

                fileInfo.ID = Convert.ToString(lstItem.FieldValues["ID"]);

                fileInfo.LastModified = Convert.ToDateTime(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.LastModified]).ToShortDateString();


                fileInfo.FileName = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileLeafRef]);

                fileInfo.FSObJType = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FSObjType]);

                fileInfo.FileID = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.UniqueId]);

                fileInfo.FileType = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileType]);

                fileInfo.RelativeURL = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileRef]);

                fileInfo.FileDirPath = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileDirRef]);


                fileInfo.CreatedBy = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.CreatedBy]).LookupValue);

                fileInfo.CreatedByEmail = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.CreatedBy]).Email);

                fileInfo.CreatedTime = ((DateTime)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.Created]).ToString("MM/dd/yyyy");

                fileInfo.ModifiedTime = ((DateTime)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.Modified]).ToString("MM/dd/yyyy");

                fileInfo.ModifiedBy = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.ModifiedBy]).LookupValue);

                fileInfo.ModifiedByEmail = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.ModifiedBy]).Email);

                fileInfo.FileSize_KB = Convert.ToString(Math.Round((Convert.ToDouble(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileSize]) / 1024), 2)); //File size in KB  

                fileInfo.HtmlFileType = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.HTMLFileType]);

                fileInfo.ItemChildCount = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.ItemChildCount]);

                fileInfo.FolderChildCount = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FolderChildCount]);

            }

            else if (lstItem.FileSystemObjectType == FileSystemObjectType.Folder)

            {

                fileInfo.ID = Convert.ToString(lstItem.Id);

                fileInfo.FileName = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileLeafRef]);

                fileInfo.FSObJType = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FSObjType]);

                fileInfo.FileID = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.UniqueId]);

                fileInfo.FileType = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileType]);

                fileInfo.RelativeURL = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileRef]);

                fileInfo.FileDirPath = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileDirRef]);


                fileInfo.CreatedBy = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.CreatedBy]).LookupValue);

                fileInfo.CreatedByEmail = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.CreatedBy]).Email);

                fileInfo.CreatedTime = ((DateTime)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.Created]).ToString("MM/dd/yyyy");

                fileInfo.ModifiedTime = ((DateTime)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.Modified]).ToString("MM/dd/yyyy");

                fileInfo.ModifiedBy = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.ModifiedBy]).LookupValue);

                fileInfo.ModifiedByEmail = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.ModifiedBy]).Email);

                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.LibraryCommonField.FileSize) && Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileSize]) != "")

                    fileInfo.FileSize_KB = Convert.ToString(Math.Round((Convert.ToDouble(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileSize]) / 1024), 2)); //File size in KB  

                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.LibraryCommonField.HTMLFileType))

                    fileInfo.HtmlFileType = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.HTMLFileType]);

                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.LibraryCommonField.ItemChildCount))

                    fileInfo.ItemChildCount = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.ItemChildCount]);

                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.LibraryCommonField.FolderChildCount))

                    fileInfo.FolderChildCount = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FolderChildCount]);


            }

            #endregion

            return fileInfo;

        }

        private static Common.FolderInformation getFolderInformation(ClientContext ctx, ListItem lstItem)

        {

            Common.FolderInformation folderInfo = new Common.FolderInformation();

            //ctx.Load(lstItem);

            //ctx.Load(lstItem.ContentType);

            //ctx.ExecuteQuery();

            //var contetTypeId = lstItem.ContentType.Id;

            //var currcontetTypeName = lstItem.ContentType.Name;

            #region call when ListItem type is Folder            

            if (lstItem.FileSystemObjectType == FileSystemObjectType.Folder)

            {

                folderInfo.ID = Convert.ToString(lstItem.Id);

                folderInfo.FolderName = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileLeafRef]);

                folderInfo.FSObJType = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FSObjType]);

                folderInfo.FolderID = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.UniqueId]);

                folderInfo.FolderType = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileType]);

                folderInfo.RelativeURL = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileRef]);

                folderInfo.FolderDirPath = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileDirRef]);


                folderInfo.CreatedBy = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.CreatedBy]).LookupValue);

                folderInfo.CreatedByEmail = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.CreatedBy]).Email);

                folderInfo.CreatedTime = ((DateTime)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.Created]).ToString("MM/dd/yyyy");

                folderInfo.ModifiedTime = ((DateTime)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.Modified]).ToString("MM/dd/yyyy");

                folderInfo.ModifiedBy = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.ModifiedBy]).LookupValue);

                //fileInfo.ModifiedByEmail = lstItem.File.ModifiedBy.Email;

                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.LibraryCommonField.FileSize) && Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileSize]) != "")

                    folderInfo.FolderSize_KB = Convert.ToString(Math.Round((Convert.ToDouble(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileSize]) / 1024), 2)); //File size in KB  

                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.LibraryCommonField.HTMLFileType))

                    folderInfo.HtmlFileType = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.HTMLFileType]);

                //folderInfo.ContentType = currcontetTypeName;

            }

            #endregion

            return folderInfo;

        }

        private static DataTable ExportDataTable(FieldCollection fields, List<ListItem> items)

        {

            System.Data.DataTable dt = new System.Data.DataTable();

            try

            {                

                Dictionary<string, string> dic = new Dictionary<string, string>();

                dic.Add(CommonSiteCloumn.LibraryCommonField.ID, CommonSiteCloumn.FileDataTableHeader.ID);

                dic.Add(CommonSiteCloumn.LibraryCommonField.FileLeafRef, CommonSiteCloumn.FileDataTableHeader.FileName);

                dic.Add(CommonSiteCloumn.LibraryCommonField.UniqueId, CommonSiteCloumn.FileDataTableHeader.FileID);

                dic.Add(CommonSiteCloumn.LibraryCommonField.FileDirRef, CommonSiteCloumn.FileDataTableHeader.FileDirPath);

                dic.Add(CommonSiteCloumn.LibraryCommonField.FileRef, CommonSiteCloumn.FileDataTableHeader.RelativeURL);

                dic.Add(CommonSiteCloumn.LibraryCommonField.FileType, CommonSiteCloumn.FileDataTableHeader.FileType);

                dic.Add(CommonSiteCloumn.LibraryCommonField.HTMLFileType, CommonSiteCloumn.FileDataTableHeader.HtmlFileType);

                dic.Add(CommonSiteCloumn.LibraryCommonField.CreatedBy, CommonSiteCloumn.FileDataTableHeader.CreatedBy);                

                dic.Add(CommonSiteCloumn.LibraryCommonField.CheckoutUser, CommonSiteCloumn.FileDataTableHeader.CheckedOutByUser);

                dic.Add(CommonSiteCloumn.LibraryCommonField.ModifiedBy, CommonSiteCloumn.FileDataTableHeader.ModifiedBy);

                dic.Add(CommonSiteCloumn.LibraryCommonField.Modified, CommonSiteCloumn.FileDataTableHeader.LastModified);

                dic.Add(CommonSiteCloumn.LibraryCommonField.Created, CommonSiteCloumn.FileDataTableHeader.CreatedTime);

                var fieldValues = fields.Cast<Field>().Select(f => f).ToList();

                foreach (var field in fieldValues)

                {

                    if (!dic.ContainsKey(field.InternalName))

                    {

                        dic.Add(field.InternalName, field.Title);

                    }

                }

                dt = MakeDataTable.getDataTableFromListItemCollection(items);

                if (dt != null)

                {

                    if (dt.Rows.Count > 0)

                    {

                        foreach (var column in dt.Columns.Cast<DataColumn>().ToList())

                        {

                            if (!dic.ContainsKey(column.ColumnName))

                            {

                                dt.Columns.Remove(column.ColumnName);

                            }

                        }

                        int ordinalPos = 0;

                        foreach (var key in dic.Keys)

                        {

                            var column = dt.Columns.Cast<DataColumn>().Where(dc => dc.ColumnName.Equals(key)).FirstOrDefault();

                            if (column != null)

                            {

                                column.SetOrdinal(ordinalPos++);

                            }

                        }                        

                        foreach (var column in dt.Columns.Cast<DataColumn>().ToList())

                        {

                            if (dic.ContainsKey(column.ColumnName))

                            {

                                column.ColumnName = dic[column.ColumnName];

                            }

                        }

                    }

                }

            }

            catch (Exception ex)

            {

            }

            return dt;

        }

        private static Common.DocumentSetInformation getdocumentSetInformation(ClientContext ctx, ListItem lstItem, string libraryName)

        {

            Common.DocumentSetInformation documentSetInformation = new Common.DocumentSetInformation();

            //var contetTypeId = lstItem.ContentType.Id;

            //var currcontetTypeName = lstItem.ContentType.Name;

            #region call when ListItem type is Folder            

            if (lstItem.FileSystemObjectType == FileSystemObjectType.Folder)

            {

                documentSetInformation.DS_ListName = libraryName;

                documentSetInformation.ID = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.ID]);

                documentSetInformation.InsuredName = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileLeafRef]);


                documentSetInformation.FSObJType = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FSObjType]);

                documentSetInformation.FolderID = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.UniqueId]);

                documentSetInformation.FolderType = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileType]);

                documentSetInformation.RelativeURL = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileRef]);

                documentSetInformation.FolderDirPath = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileDirRef]);


                documentSetInformation.CreatedBy = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.CreatedBy]).LookupValue);

                documentSetInformation.CreatedByEmail = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.CreatedBy]).Email);

                documentSetInformation.CreatedTime = ((DateTime)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.Created]).ToString("MM/dd/yyyy");

                documentSetInformation.ModifiedTime = ((DateTime)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.Modified]).ToString("MM/dd/yyyy");

                documentSetInformation.ModifiedBy = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.ModifiedBy]).LookupValue);

                documentSetInformation.ModifiedByEmail = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.ModifiedBy]).Email);


                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.LibraryCommonField.SMTotalFileStreamSize) && Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.SMTotalFileStreamSize]) != "")

                    documentSetInformation.FolderSize_KB = Convert.ToString(Math.Round((Convert.ToDouble(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.SMTotalFileStreamSize]) / 1024), 2)); //File size in KB  

                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.LibraryCommonField.HTMLFileType) && lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.HTMLFileType] != null)

                    documentSetInformation.HtmlFileType = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.LibraryCommonField.HTMLFileType]);


                #region set all document set meta data field


                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.UnderWritingField.MRSIEffectiveDate) && lstItem.FieldValues[CommonSiteCloumn.UnderWritingField.MRSIEffectiveDate] != null)

                    documentSetInformation.DS_MRSI_EffectiveDat = ((DateTime)lstItem.FieldValues[CommonSiteCloumn.UnderWritingField.MRSIEffectiveDate]).ToString("MM/dd/yyyy");

                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.UnderWritingField.MRSIEffYear))

                    documentSetInformation.DS_MRSI_EffYear = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.UnderWritingField.MRSIEffYear]);


                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.UnderWritingField.MRSILOB) && lstItem.FieldValues[CommonSiteCloumn.UnderWritingField.MRSILOB] != null)

                {

                    documentSetInformation.DS_MRSI_LOB = Convert.ToString(string.Join(";", ((string[])lstItem.FieldValues[CommonSiteCloumn.UnderWritingField.MRSILOB])));

                }

                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.UnderWritingField.MRSINANDA))

                    documentSetInformation.DS_MRSI_NANDA = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.UnderWritingField.MRSINANDA]);


                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.UnderWritingField.MRSIProduct) && lstItem.FieldValues[CommonSiteCloumn.UnderWritingField.MRSIProduct] != null)

                {

                    documentSetInformation.DS_MRSI_Product = string.Join(";", ((string[])lstItem.FieldValues[CommonSiteCloumn.UnderWritingField.MRSIProduct]));

                }

                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.UnderWritingField.MRSICategory) && lstItem.FieldValues[CommonSiteCloumn.UnderWritingField.MRSICategory] != null)

                    documentSetInformation.DS_MRSI_Category = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.UnderWritingField.MRSICategory]);


                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.UnderWritingField.MRSISubcategory) && lstItem.FieldValues[CommonSiteCloumn.UnderWritingField.MRSISubcategory] != null)

                    documentSetInformation.DS_MRSI_Subcategory = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.UnderWritingField.MRSISubcategory]);


                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.UnderWritingField.MRSIUW) && (FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.UnderWritingField.MRSIUW] != null)

                    documentSetInformation.DS_MRSI_UW = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.UnderWritingField.MRSIUW]).LookupValue);


                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.UnderWritingField.Broker) && lstItem.FieldValues[CommonSiteCloumn.UnderWritingField.Broker] != null)

                    documentSetInformation.DS_Broker = Convert.ToString(lstItem.FieldValues[CommonSiteCloumn.UnderWritingField.Broker]);


                //if (lstItem.FieldValues.ContainsKey("DocumentSetDescription") && lstItem.FieldValues["DocumentSetDescription"] != null)

                //    documentSetInformation.DS_Description = Convert.ToString((lstItem.FieldValuesAsText["DocumentSetDescription"]));


                if (lstItem.FieldValues.ContainsKey(CommonSiteCloumn.UnderWritingField.CheckoutUser))

                {

                    var checkoutuser = ((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.UnderWritingField.CheckoutUser]);

                    if (checkoutuser != null)

                        documentSetInformation.DS_CheckoutUser = Convert.ToString(((FieldUserValue)lstItem.FieldValues[CommonSiteCloumn.UnderWritingField.CheckoutUser]).LookupValue);

                }

                documentSetInformation.ItemChildCount = Convert.ToString(lstItem.FieldValues["ItemChildCount"]);

                documentSetInformation.FolderChildCount = Convert.ToString(lstItem.FieldValues["FolderChildCount"]);

                #endregion

            }

            #endregion

            return documentSetInformation;

        }

        public static void AddKeywords(Microsoft.SharePoint.Client.ListItem item, string keywordString)

        {

            string[] keywords = keywordString.Split(',').Select(s => s.Trim()).ToArray();

            if (item != null)

            {

                //KeywordsManager.SetTaxKeywordValue(item, keywords);

            }

        }

        public static void UploadFileToSharePoint(ClientContext CContext, List DocumentLibrary, Folder Clientfolder, MemoryStream FileContent, string FileName)

        {

            try

            {

                #region Insert the data

                using (CContext)

                {

                    Microsoft.SharePoint.Client.Web web = CContext.Web;

                    Microsoft.SharePoint.Client.FileCreationInformation newFile = new Microsoft.SharePoint.Client.FileCreationInformation();

                    //byte[] FileContent = System.IO.File.ReadAllBytes(FileName);

                    newFile.ContentStream = new MemoryStream(FileContent.ToArray());

                    //newFile.Content = FileContent.ToArray();

                    newFile.Url = FileName;

                    newFile.Overwrite = true;

                    //newFile.Url = Path.GetFileName(FileName);

                    //Microsoft.SharePoint.Client.List DocumentLibrary = web.Lists.GetByTitle(DocLibrary);

                    //SP.Folder folder = DocumentLibrary.RootFolder.Folders.GetByUrl(ClientSubFolder);

                    //Microsoft.SharePoint.Client.Folder Clientfolder = DocumentLibrary.RootFolder.Folders.Add(ClientSubFolder);

                    //Clientfolder.Update();

                    Microsoft.SharePoint.Client.File uploadFile = Clientfolder.Files.Add(newFile);


                    //CContext.Load(DocumentLibrary);

                    CContext.ExecuteQuery();

                    CContext.Load(uploadFile);

                    CContext.ExecuteQuery();

                    filesCount = filesCount + 1;

                    Log.Instance.Trace("Total number of Files copying. Count: " + filesCount.ToString());

                    //newFile.ContentStream.Close();

                    //CContext.ExecuteQuery();

                    //Console.ForegroundColor = ConsoleColor.Green;

                    //Console.WriteLine("The File has been uploaded" + Environment.NewLine + "FileUrl -->"+uploadFile.ServerRelativeUrl); 

                }


                #endregion

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

            finally

            {

                //Console.ReadLine();

            }

        }


        /// <summary>

        /// Partition a list of elements into a smaller group of elements

        /// </summary>

        /// <typeparam name="T"></typeparam>

        /// <param name="list"></param>

        /// <param name="totalPartitions"></param>

        /// <returns></returns>

        public static List<T>[] Partition<T>(List<T> list, int totalPartitions)

        {

            if (list == null)

                throw new ArgumentNullException("list");


            if (totalPartitions < 1)

                throw new ArgumentOutOfRangeException("totalPartitions");


            List<T>[] partitions = new List<T>[totalPartitions];


            int maxSize = (int)Math.Ceiling(list.Count / (double)totalPartitions);

            int k = 0;


            for (int i = 0; i < partitions.Length; i++)

            {

                partitions[i] = new List<T>();

                for (int j = k; j < k + maxSize; j++)

                {

                    if (j >= list.Count)

                        break;

                    partitions[i].Add(list[j]);

                }

                k += maxSize;

            }


            return partitions;

        }


        private static void setSiteColumnFieldValue(ListItem item, DataTable dataTable)

        {

            DataRow dr = dataTable.Rows.Cast<DataRow>().LastOrDefault();

            foreach (var obj in item.FieldValues)

            {

                var column = dataTable.Columns.Cast<System.Data.DataColumn>().ToList().Where(dc => dc.ColumnName.Equals(obj.Key)).FirstOrDefault();

                if (column == null)

                {

                    if (obj.Value != null)

                    {

                        string key = obj.Key;

                        string type = obj.Value.GetType().FullName;


                        if (type == "Microsoft.SharePoint.Client.FieldLookupValue")

                        {

                            dr[obj.Key] = ((FieldLookupValue)obj.Value).LookupValue;

                        }

                        else if (type == "Microsoft.SharePoint.Client.FieldUserValue")

                        {

                            dr[obj.Key] = ((FieldUserValue)obj.Value).LookupValue;

                        }

                        else if (type == "Microsoft.SharePoint.Client.FieldUserValue[]")

                        {

                            FieldUserValue[] multValue = (FieldUserValue[])obj.Value;

                            foreach (FieldUserValue fieldUserValue in multValue)

                            {

                                dr[obj.Key] += (fieldUserValue).LookupValue;

                            }

                        }

                        else if (type == "System.DateTime")

                        {

                            if (obj.Value.ToString().Length > 0)

                            {

                                var date = obj.Value.ToString().Split(' ');

                                if (date[0].Length > 0)

                                {

                                    dr[obj.Key] = date[0];

                                }

                            }

                        }

                        else

                        {

                            dr[obj.Key] = obj.Value;

                        }

                    }

                    else

                    {

                        dr[obj.Key] = null;

                    }

                }

            }

        }

    }

#############################################


 internal class DocumentSetExtension

    {

        private static int numberofFileCopie = 0;

        public static async Task CopyAllDocumentSetWithMetaData(ClientContext SourceContext,ClientContext DestinationContext,string SourceListName,string TargetListName,string docSetContentTypeName)

        {

            try

            {              


                List TargetList = DestinationContext.Web.Lists.GetByTitle(TargetListName);

                DestinationContext.Load(TargetList.RootFolder);

                DestinationContext.Load(TargetList.Fields, fc => fc.Where(f => f.Hidden == false && f.ReadOnlyField == false && f.InternalName != "Attachments" && f.InternalName != "ContentType"));

                DestinationContext.ExecuteQuery();

                var dsDestinationContentType = TargetList.GetContentTypeByName(docSetContentTypeName);

                var matchDSDestinationCTID = TargetList.BestMatchContentTypeId(dsDestinationContentType.Id.StringValue);


                List SourceList = SourceContext.Web.Lists.GetByTitle(SourceListName);

                SourceContext.Load(SourceList.RootFolder);

                SourceContext.Load(SourceList.Fields, fc => fc.Where(f => f.Hidden == false && f.ReadOnlyField == false && f.InternalName != "Attachments" && f.InternalName != "ContentType"));

                SourceContext.ExecuteQuery();

                var dsSourceContentType = TargetList.GetContentTypeByName(docSetContentTypeName);

                var matchDSSourceCTID = TargetList.BestMatchContentTypeId(dsSourceContentType.Id.StringValue);



                IList<Task> oSourceTask = new List<Task>();

                List<Folder> oSourceFolders = new List<Folder>();

                List<ListItem> odsSourceListItems = new List<ListItem>();

                List<ListItemCollection> listItemCollection = Task.Run(() => csomListCommon.GetSharePointDataAsync(SourceContext, SourceListName)).GetAwaiter().GetResult();

                int left = Console.CursorLeft;

                int top = Console.CursorTop;

                listItemCollection.ForEach(listItems =>

                {

                    var foldercollection = listItems.Cast<ListItem>().Where(li => li.FileSystemObjectType == FileSystemObjectType.Folder).Select(li => li).ToList();

                    odsSourceListItems.AddRange(foldercollection);

                    Console.SetCursorPosition(left, top);

                    Console.WriteLine(string.Format("Source DocumentSet Count: {0}", odsSourceListItems.Count.ToString()));

                });

                left = Console.CursorLeft;

                top = Console.CursorTop;

                foreach (var folder in odsSourceListItems)

                {

                    if (folder.FieldValues.ContainsKey(CommonSiteCloumn.LibraryCommonField.FileRef))

                    {

                        string folderserverRelativeURL = folder.FieldValues[CommonSiteCloumn.LibraryCommonField.FileRef].ToString();

                        var dsFolder = SourceContext.Web.GetFolderByServerRelativeUrl(folderserverRelativeURL);

                        oSourceFolders.Add(dsFolder);

                        SourceContext.Load(dsFolder, f => f, f => f.ListItemAllFields, f => f.ListItemAllFields.ContentType, f => f.Files, f => f.Files.Include(i => i, i => i.ListItemAllFields));

                        oSourceTask.Add(SourceContext.ExecuteQueryAsync());

                        Console.SetCursorPosition(left, top);

                        Console.WriteLine(string.Format("Async Task Count: {0}", oSourceTask.Count.ToString()));

                    }

                }

                try

                {

                    Task[] tasks = oSourceTask.Cast<Task>().ToArray();

                    await Task.WhenAll(tasks).ContinueWith(t => { Console.WriteLine("Error found in task continuation. Exception", t.Exception.Message); }, TaskContinuationOptions.OnlyOnFaulted).ConfigureAwait(false);

                    try

                    {

                        int TaskResultset = 0;

                        left = Console.CursorLeft;

                        top = Console.CursorTop;

                        foreach (var t in tasks)

                        {

                            await t;

                            Console.SetCursorPosition(left, top);

                            if (t.Status == TaskStatus.RanToCompletion)

                            {

                                Console.WriteLine("Total Task completed: {0} and Task Status is {1}", TaskResultset.ToString(), t.Status.ToString());

                            }

                            else if (t.Status == TaskStatus.Faulted)

                            {

                                Console.WriteLine("Task faulted");

                            }

                            else { Console.WriteLine(t.Status.ToString()); }

                            TaskResultset++;

                        }

                    }

                    catch

                    {

                    }

                }

                catch (Exception ex)

                {

                    Console.WriteLine("Task When All Error: {0}", ex.Message);

                }

                finally

                {

                    int dsCount = 0;

                    int fileCount = 0;

                  

                    foreach (var item in oSourceFolders)

                    {

                        try

                        {

                            if (item != null)

                            {

                                if (item.ListItemAllFields.FieldValues.Count > 0)

                                {

                                    dsCount++;

                                    string DS = Convert.ToString(item.ListItemAllFields.FieldValues[CommonSiteCloumn.LibraryCommonField.FileLeafRef]);

                                    string DSRelativeUrl = Convert.ToString(item.ListItemAllFields.FieldValues[CommonSiteCloumn.LibraryCommonField.FileRef]);

                                    Log.Instance.Debug("SRNO: {0} Document Set Name: {1} and DocSetURL: {2}", dsCount.ToString(), DS, DSRelativeUrl);

                                    var newTargetDSFolder = await createNewDocumentSet(DestinationContext, TargetList, matchDSDestinationCTID, DS);                                    

                                    if (newTargetDSFolder == null)

                                    {

                                        FolderExtensions.updateDocumentSetMetaData(SourceContext, DestinationContext, item, newTargetDSFolder, SourceList.Fields, TargetList.Fields);

                                        var targetDSFileCollection = newTargetDSFolder.Files.Cast<Microsoft.SharePoint.Client.File>().ToList();

                                        if (item.Files != null)

                                        {

                                            Dictionary<Microsoft.SharePoint.Client.File, Microsoft.SharePoint.Client.File> dictionaryFiles = new Dictionary<Microsoft.SharePoint.Client.File, Microsoft.SharePoint.Client.File>();

                                            foreach (var sourcefile in item.Files)

                                            {

                                                try

                                                {

                                                    fileCount++;

                                                    string fileName = Convert.ToString(sourcefile.ListItemAllFields.FieldValues[CommonSiteCloumn.LibraryCommonField.FileLeafRef]);

                                                    string fileRelativeUrl = Convert.ToString(sourcefile.ListItemAllFields.FieldValues[CommonSiteCloumn.LibraryCommonField.FileRef]);

                                                    string fileType = Convert.ToString(sourcefile.ListItemAllFields.FieldValues[CommonSiteCloumn.LibraryCommonField.FileType]);

                                                    Log.Instance.Trace("SRNO: {0} File Name: {1} and URL: {2}", fileCount.ToString(), fileName, fileRelativeUrl);

                                                    var isFileAlready = targetDSFileCollection.Where(fc => String.Equals(fc.ListItemAllFields.FieldValues[CommonSiteCloumn.LibraryCommonField.FileLeafRef].ToString(), fileName)).FirstOrDefault();                                                    

                                                    if(isFileAlready == null)

                                                    {

                                                        

                                                        var fileStreamResult = sourcefile.OpenBinaryStream();

                                                        SourceContext.Load(sourcefile);

                                                        SourceContext.ExecuteQuery();

                                                        MemoryStream datastream = new MemoryStream();

                                                        await fileStreamResult.Value.CopyToAsync(datastream);


                                                        await DestinationContext.ExecuteQueryAsync();

                                                        var newFile = await UploadFiletoSharePoint(DestinationContext, TargetList, newTargetDSFolder, datastream, fileName);

                                                        if (newFile != null)

                                                        {

                                                            dictionaryFiles.Add(sourcefile, newFile);

                                                            Log.Instance.Info("SRNO '{0}' Copy file '{1}' to '{2}'", numberofFileCopie.ToString(), fileRelativeUrl, newFile.ServerRelativeUrl);

                                                          

                                                        }

                                                    }

                                                }

                                                catch (Exception ex)

                                                {

                                                    Console.WriteLine("File Error: {0}", ex.Message);

                                                }

                                            }

                                            if (dictionaryFiles.Count() > 0)

                                            {

                                                await updateMultipleFileMetaData(SourceContext, DestinationContext, dictionaryFiles, SourceList.Fields, TargetList.Fields);

                                            }

                                        }

                                    }

                                }

                            }

                        }

                        catch (Exception ex)

                        {


                        }

                    }

                }

            }

            catch (Exception ex)

            {

            }

        }

        public static async Task<Folder> createNewDocumentSet(ClientContext DestinationContext, List TargetList,ContentTypeId matchdocSetCTID, string documentSetName)

        {

           Folder folderTask = null;

            try

            {

                         

                var dsFolderTask=TargetList.RootFolder.CreateDocumentSet(documentSetName, matchdocSetCTID);

                await DestinationContext.ExecuteQueryAsync();

                folderTask = DestinationContext.Web.GetFolderByServerRelativeUrl(TargetList.RootFolder.ServerRelativeUrl + "/" + documentSetName);

                Log.Instance.Trace(string.Format("New Account '{0}' has created successfully...", documentSetName));

                if (folderTask != null)

                {

                    DestinationContext.Load(folderTask, f => f, f => f.ListItemAllFields, f => f.ListItemAllFields.ContentType, f => f.Files, f => f.Files.Include(i => i, i => i.ListItemAllFields));

                    await DestinationContext.ExecuteQueryAsync();                    

                }

            }

            catch (Exception ex)

            {

                string exString = Helper.ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

            return folderTask;

        }


        private static async Task<Microsoft.SharePoint.Client.File> UploadFiletoSharePoint(ClientContext CContext, List DocumentLibrary, Folder Clientfolder, MemoryStream FileContent, string FileName)

        {

            Microsoft.SharePoint.Client.FileCreationInformation newFile = new Microsoft.SharePoint.Client.FileCreationInformation();

            newFile.ContentStream = new MemoryStream(FileContent.ToArray());

            

            newFile.Url = FileName;

            newFile.Overwrite = true;

            Microsoft.SharePoint.Client.File uploadFile = Clientfolder.Files.Add(newFile);


         

            await CContext.ExecuteQueryAsync();

            CContext.Load(uploadFile, f => f, f => f.ListItemAllFields);

            await CContext.ExecuteQueryAsync();

            numberofFileCopie = numberofFileCopie + 1;            

           

            return uploadFile;

        }

        private static async Task updateFileMetaData(ClientContext SourceCtx, ClientContext TargetCtx, Microsoft.SharePoint.Client.File DS_SourceFile, 

            Microsoft.SharePoint.Client.File DS_TargetFile, FieldCollection Sourcefields, FieldCollection Targetfields)

        {

            try

            {                

                Microsoft.SharePoint.Client.File DS_SourceFileObj = SourceCtx.Web.GetFileByServerRelativeUrl(DS_SourceFile.ServerRelativeUrl);

                SourceCtx.Load(DS_SourceFileObj, f => f, f => f.ListItemAllFields);

                await SourceCtx.ExecuteQueryAsync();


                Microsoft.SharePoint.Client.File DS_TargetFileObj = TargetCtx.Web.GetFileByServerRelativeUrl(DS_TargetFile.ServerRelativeUrl);

                TargetCtx.Load(DS_TargetFileObj, dsf => dsf, dsf => dsf.ListItemAllFields);

                await TargetCtx.ExecuteQueryAsync();


                ListItem DS_SourceItem = DS_SourceFileObj.ListItemAllFields;

                ListItem DS_TargetItem = DS_TargetFileObj.ListItemAllFields;


                                      

                Sourcefields.Cast<Field>().ToList().ForEach(sf =>

                {

                    string srcFieldName = sf.Title;

                    string srcFieldInternalName = sf.InternalName;

                    if (DS_SourceItem.FieldValues.ContainsKey(srcFieldInternalName))

                    {

                        if (DS_TargetItem.FieldValues.ContainsKey(srcFieldInternalName))

                        {

                            DS_TargetItem[srcFieldInternalName] = DS_SourceItem.FieldValues[srcFieldInternalName];

                        }

                    }

                });

                try

                {

                    var Author = TargetCtx.Web.EnsureUser(((FieldUserValue)DS_SourceItem["Author"]).Email);

                    DS_TargetItem["Author"] = Author;

                    var Editor = TargetCtx.Web.EnsureUser(((FieldUserValue)DS_SourceItem["Editor"]).Email);

                    DS_TargetItem["Editor"] = Editor;

                    DS_TargetItem["Created"] = DS_SourceItem["Created"];

                    DS_TargetItem["Modified"] = DS_SourceItem["Modified"];


                    DS_TargetItem.Update();

                    await TargetCtx.ExecuteQueryAsync();

                }

                catch (Exception ex)

                {

                    string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                    Log.Instance.Warn(exString);

                }

                Log.Instance.Trace(string.Format("File '{0}' meta data has updated successfully...", DS_TargetItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileLeafRef]));

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

        }


        private static async Task updateMultipleFileMetaData(ClientContext SourceCtx, ClientContext TargetCtx, Dictionary<Microsoft.SharePoint.Client.File,Microsoft.SharePoint.Client.File> dictionaryFileCollection, FieldCollection Sourcefields, FieldCollection Targetfields)

        {

            try

            {

                int runExecuteQuery = 100;

                int posCount = 0;

                foreach (var keyValuePair in dictionaryFileCollection)

                {

                    Microsoft.SharePoint.Client.File DS_SourceFile = keyValuePair.Key;

                    Microsoft.SharePoint.Client.File DS_TargetFile = keyValuePair.Value;


                   



                    

                    ListItem DS_SourceItem = DS_SourceFile.ListItemAllFields;

                    ListItem DS_TargetItem = DS_TargetFile.ListItemAllFields;

                                       

                    Sourcefields.Cast<Field>().ToList().ForEach(sf =>

                    {

                        string srcFieldName = sf.Title;

                        string srcFieldInternalName = sf.InternalName;

                        if (DS_SourceItem.FieldValues.ContainsKey(srcFieldInternalName))

                        {

                            if (DS_TargetItem.FieldValues.ContainsKey(srcFieldInternalName))

                            {

                                DS_TargetItem[srcFieldInternalName] = DS_SourceItem.FieldValues[srcFieldInternalName];

                            }

                        }

                    });

                    try

                    {

                        var Author = TargetCtx.Web.EnsureUser(((FieldUserValue)DS_SourceItem["Author"]).Email);

                        DS_TargetItem["Author"] = Author;

                        var Editor = TargetCtx.Web.EnsureUser(((FieldUserValue)DS_SourceItem["Editor"]).Email);

                        DS_TargetItem["Editor"] = Editor;

                        DS_TargetItem["Created"] = DS_SourceItem["Created"];

                        DS_TargetItem["Modified"] = DS_SourceItem["Modified"];


                        DS_TargetItem.Update();

                        posCount++;                        

                        if (posCount > runExecuteQuery)

                        {

                            await TargetCtx.ExecuteQueryAsync();

                        }

                    }

                    catch (Exception ex)

                    {

                        string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                        Log.Instance.Warn(exString);

                    }

                    string sourcefileRelURL = DS_SourceItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileLeafRef].ToString();

                    string targetfileRelURL = DS_TargetItem.FieldValues[CommonSiteCloumn.LibraryCommonField.FileLeafRef].ToString();

                    Log.Instance.Trace(string.Format("Copy meta data of File '{0}' to '{1}'", sourcefileRelURL, targetfileRelURL));

                }

                await TargetCtx.ExecuteQueryAsync();

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Error(exString);

            }

        }


        static public byte[] FileToByteArray(string path)

        {

            byte[] binary=null;

            var bytearray = System.IO.File.ReadAllBytes(path);

            binary = bytearray;

            return binary;

       }

    }

No comments:

Post a Comment