Wednesday, 30 March 2022

Common Class use in Copy document sets

 public class Common

    {

        public class ExcelFileInformation

        {

            //private string _siteId;

            //private string _webId;

            //private string _listId;

            private string _listName;

            private string _FileIDinlist;

            private string _contentType;

            private string _Name;

            private string _Author;

            private string _checkedOutByUser;

            private string _ModifiedBy;

            private string _LastModified;

            private string _title;

            private string _typedObject;

            private string _uniqueId;

            private string _fileType;

            private string _htmlfileType;

            private string _relativeURL;

            private string _fileDirPath;

            private string _CreatedTime;

            private string _FileSize_KB;

            private string _FSObJType;

            private string _createdByEmail;

            private string _modifiedByEmail;

            private string _ModifiedTime;

            private string _versionCount;

            private string _folderChildCount;

            private string _ItemChildCount;

            private ListItem _listItem;


            //public string SiteId

            //{

            //    get { return _siteId; }

            //    set { _siteId = value; }

            //}

            //public string WebId

            //{

            //    get { return _webId; }

            //    set { _webId = value; }

            //}

            public string ListName

            {

                get { return _listName; }

                set { _listName = value; }

            }

            public string FileIDinList

            {

                get { return _FileIDinlist; }

                set { _FileIDinlist = value; }

            }

            public string ContentType

            {

                get { return _contentType; }

                set { _contentType = value; }

            }

            public string FileName

            {

                get { return _Name; }

                set { _Name = value; }

            }

            public string Title

            {

                get { return _title; }

                set { _title = value; }

            }

            public string FileID

            {

                get { return _uniqueId; }

                set { _uniqueId = value; }

            }                       

            public string FileDirPath

            {

                get { return _fileDirPath; }

                set { _fileDirPath = value; }

            }

            public string RelativeURL

            {

                get { return _relativeURL; }

                set { _relativeURL = value; }

            }

            public string FileType

            {

                get { return _fileType; }

                set { _fileType = value; }

            }

            public string HtmlFileType

            {

                get { return _htmlfileType; }

                set { _htmlfileType = value; }

            }

            public string TypedObject

            {

                get { return _typedObject; }

                set { _typedObject = value; }

            }

            public string FileSize_KB

            {

                get { return _FileSize_KB; }

                set { _FileSize_KB = value; }

            }

            public string VersionsCount

            {

                get { return _versionCount; }

                set { _versionCount = value; }

            }

            public string FSObJType

            {

                get { return _FSObJType; }

                set { _FSObJType = value; }

            }

            public string CreatedBy

            {

                get { return _Author; }

                set { _Author = value; }

            }

            public string CreatedByEmail

            {

                get { return _createdByEmail; }

                set

                {

                    _createdByEmail = value;

                }

            }

            public string CheckedOutByUser

            {

                get { return _checkedOutByUser; }

                set { _checkedOutByUser = value; }

            }

            public string ModifiedBy

            {

                get { return _ModifiedBy; }

                set { _ModifiedBy = value; }

            }

            public string ModifiedByEmail

            {

                get { return _modifiedByEmail; }

                set { _modifiedByEmail = value; }

            }

            public string LastModified

            {

                get { return _LastModified; }

                set { _LastModified = value; }

            }

            public string CreatedTime

            {

                get { return _CreatedTime; }

                set { _CreatedTime = value; }

            }

            public string ModifiedTime

            {

                get { return _ModifiedTime; }

                set { _ModifiedTime = value; }

            }

            public string FolderChildCount

            {

                get { return _folderChildCount; }

                set { _folderChildCount = value; }

            }

            public string ItemChildCount

            {

                get { return _ItemChildCount; }

                set { _ItemChildCount = value; }

            }

            public ListItem FileListItem

            {

                get { return _listItem; }

                set { _listItem = value; }

            }

        }

        public class FileInformation

        {            

            private string _listName;

            private string _FileIDinlist;

            //private string _contentType;

            private string _Name;

            private string _Author;

            private string _checkedOutByUser;

            private string _ModifiedBy;

            private string _LastModified;

            private string _title;

            private string _typedObject;

            private string _uniqueId;

            private string _fileType;

            private string _htmlfileType;

            private string _relativeURL;

            private string _fileDirPath;

            private string _CreatedTime;

            private string _FileSize_KB;

            private string _FSObJType;

            private string _createdByEmail;

            private string _modifiedByEmail;

            private string _ModifiedTime;

            private string _versionCount;

            private string _folderChildCount;

            private string _ItemChildCount;

                        

            public string ListName

            {

                get { return _listName; }

                set { _listName = value; }

            }

            public string ID

            {

                get { return _FileIDinlist; }

                set { _FileIDinlist = value; }

            }

            //public string ContentType

            //{

            //    get { return _contentType; }

            //    set { _contentType = value; }

            //}

            public string FileName

            {

                get { return _Name; }

                set { _Name = value; }

            }

            public string Title

            {

                get { return _title; }

                set { _title = value; }

            }

            public string FileID

            {

                get { return _uniqueId; }

                set { _uniqueId = value; }

            }

            public string FileDirPath

            {

                get { return _fileDirPath; }

                set { _fileDirPath = value; }

            }

            public string RelativeURL

            {

                get { return _relativeURL; }

                set { _relativeURL = value; }

            }

            public string FileType

            {

                get { return _fileType; }

                set { _fileType = value; }

            }

            public string HtmlFileType

            {

                get { return _htmlfileType; }

                set { _htmlfileType = value; }

            }

            public string TypedObject

            {

                get { return _typedObject; }

                set { _typedObject = value; }

            }

            public string FileSize_KB

            {

                get { return _FileSize_KB; }

                set { _FileSize_KB = value; }

            }

            public string VersionsCount

            {

                get { return _versionCount; }

                set { _versionCount = value; }

            }

            public string FSObJType

            {

                get { return _FSObJType; }

                set { _FSObJType = value; }

            }

            public string CreatedBy

            {

                get { return _Author; }

                set { _Author = value; }

            }

            public string CreatedByEmail

            {

                get { return _createdByEmail; }

                set

                {

                    _createdByEmail = value;

                }

            }

            public string CheckedOutByUser

            {

                get { return _checkedOutByUser; }

                set { _checkedOutByUser = value; }

            }

            public string ModifiedBy

            {

                get { return _ModifiedBy; }

                set { _ModifiedBy = value; }

            }

            public string ModifiedByEmail

            {

                get { return _modifiedByEmail; }

                set { _modifiedByEmail = value; }

            }

            public string LastModified

            {

                get { return _LastModified; }

                set { _LastModified = value; }

            }

            public string CreatedTime

            {

                get { return _CreatedTime; }

                set { _CreatedTime = value; }

            }

            public string ModifiedTime

            {

                get { return _ModifiedTime; }

                set { _ModifiedTime = value; }

            }

            public string FolderChildCount

            {

                get { return _folderChildCount; }

                set { _folderChildCount = value; }

            }

            public string ItemChildCount

            {

                get { return _ItemChildCount; }

                set { _ItemChildCount = value; }

            }            

        }

        public class DocumentSetInformation

        {

            private string ds_listName;

            private string _FolderIDinlist;

            //private string _contentType;

            private string _Name;

            private string _Author;

            private string _ModifiedBy;            

            private string _uniqueId;

            private string _fileType;

            private string _htmlfileType;

            private string _relativeURL;

            private string _fileDirPath;

            private string _CreatedTime;

            private string _FileSize_KB;

            private string _FSObJType;

            private string _createdByEmail;

            private string _modifiedByEmail;

            private string _ModifiedTime;           

            private string _folderChildCount;

            private string _ItemChildCount;


            //private string ds_Description;

            private string ds_RelativePath;

            private string ds_MRSIEffectiveDate;

            private string ds_MRSIUW;


            private string ds_MRSIProduct;

            private string ds_MRSICategory;

            private string ds_MRSISubcategory;

            private string ds_Broker;

            private string ds_MRSINANDA;

            private string ds_MRSIEffYear;

            private string ds_MRSILOB;

            private string ds_CheckoutUser;

            public string ID

            {

                get { return _FolderIDinlist; }

                set { _FolderIDinlist = value; }

            }

            public string DS_ListName

            {

                get { return ds_listName; }

                set { ds_listName = value; }

            }


            //public string ContentType

            //{

            //    get { return _contentType; }

            //    set { _contentType = value; }

            //}

            public string InsuredName

            {

                get { return _Name; }

                set { _Name = value; }

            }           

            public string FolderID

            {

                get { return _uniqueId; }

                set { _uniqueId = value; }

            }

            public string RelativeURL

            {

                get { return _relativeURL; }

                set { _relativeURL = value; }

            }

            public string FolderDirPath

            {

                get { return _fileDirPath; }

                set { _fileDirPath = value; }

            }

            public string FolderType

            {

                get { return _fileType; }

                set { _fileType = value; }

            }

            public string HtmlFileType

            {

                get { return _htmlfileType; }

                set { _htmlfileType = value; }

            }            

            public string FolderSize_KB

            {

                get { return _FileSize_KB; }

                set { _FileSize_KB = value; }

            }

            public string FolderChildCount

            {

                get { return _folderChildCount; }

                set { _folderChildCount = value; }

            }

            public string ItemChildCount

            {

                get { return _ItemChildCount; }

                set { _ItemChildCount = value; }

            }

            public string FSObJType

            {

                get { return _FSObJType; }

                set { _FSObJType = value; }

            }

            public string CreatedBy

            {

                get { return _Author; }

                set { _Author = value; }

            }

            public string CreatedByEmail

            {

                get { return _createdByEmail; }

                set

                {

                    _createdByEmail = value;

                }

            }

            public string ModifiedBy

            {

                get { return _ModifiedBy; }

                set { _ModifiedBy = value; }

            }

            public string ModifiedByEmail

            {

                get { return _modifiedByEmail; }

                set { _modifiedByEmail = value; }

            }

            public string CreatedTime

            {

                get { return _CreatedTime; }

                set { _CreatedTime = value; }

            }

            public string ModifiedTime

            {

                get { return _ModifiedTime; }

                set { _ModifiedTime = value; }

            }         


            public string DS_MRSI_EffectiveDat

            {

                get { return ds_MRSIEffectiveDate; }

                set { ds_MRSIEffectiveDate = value; }

            }

            public string DS_MRSI_UW

            {

                get { return ds_MRSIUW; }

                set { ds_MRSIUW = value; }

            }            

            public string DS_RelativePath

            {

                get { return ds_RelativePath; }

                set { ds_RelativePath = value; }

            }            

            //public string DS_Description

            //{

            //    get { return ds_Description; }

            //    set { ds_Description = value; }

            //}

            public string DS_MRSI_Product

            {

                get { return ds_MRSIProduct; }

                set { ds_MRSIProduct = value; }

            }

            public string DS_MRSI_Category

            {

                get { return ds_MRSICategory; }

                set { ds_MRSICategory = value; }

            }

            public string DS_MRSI_Subcategory

            {

                get { return ds_MRSISubcategory; }

                set { ds_MRSISubcategory = value; }

            }

            public string DS_Broker

            {

                get { return ds_Broker; }

                set { ds_Broker = value; }

            }

            public string DS_MRSI_NANDA

            {

                get { return ds_MRSINANDA; }

                set { ds_MRSINANDA = value; }

            }

            public string DS_MRSI_EffYear

            {

                get { return ds_MRSIEffYear; }

                set { ds_MRSIEffYear = value; }

            }           

            public string DS_MRSI_LOB

            {

                get { return ds_MRSILOB; }

                set { ds_MRSILOB = value; }

            }

            public string DS_CheckoutUser

            {

                get { return ds_CheckoutUser; }

                set { ds_CheckoutUser = value; }

            }

            //MRSI-Effective-Date 

            //MRSI-UW 

            //MRSI-LOB 

            //MRSI-Product 

            //MRSI-Category

            //MRSI-Subcategory

            //Broker

            //MRSI-NANDA

            //MRSI-Eff-Year

        }

        public class MetaDataMapping

        {            

            private string _SourceListName;

            private string _targetListName;

            private string _SourceFieldName;

            private string _TargetFieldName;


            public string SourceListName

            {

                get { return _SourceListName; }

                set { _SourceListName = value; }

            }

            public string TargetListName

            {

                get { return _targetListName; }

                set { _targetListName = value; }

            }

            public string SourceFieldName

            {

                get { return _SourceFieldName; }

                set { _SourceFieldName = value; }

            }

            public string TargetFieldName

            {

                get { return _TargetFieldName; }

                set { _TargetFieldName = value; }

            }

        }

        public class FolderInformation

        {

            private string _FolderIDinlist;

            //private string _contentType;

            private string _Name;

            private string _Author;

            private string _ModifiedBy;            

            //private string _title;

            private string _typedObject;

            private string _uniqueId;

            private string _fileType;

            private string _htmlfileType;

            private string _relativeURL;

            private string _fileDirPath;

            private string _CreatedTime;

            private string _FileSize_KB;

            private string _FSObJType;

            private string _createdByEmail;

            private string _modifiedByEmail;

            private string _ModifiedTime;            



            //private string _folderRelativePath;

            //private string _folder_Eff_Year;

            //private string _folder_UW;

            //private string _folder_AccountName;

            //private string _folder_Category;

            //private string _folder_SubCategory;

            //private string _folder_Product;

            //private string _folder_EffectiveDate;


            public string ID

            {

                get { return _FolderIDinlist; }

                set { _FolderIDinlist = value; }

            }

            //public string ContentType

            //{

            //    get { return _contentType; }

            //    set { _contentType = value; }

            //}

            public string FolderName

            {

                get { return _Name; }

                set { _Name = value; }

            }

            //public string Title

            //{

            //    get { return _title; }

            //    set { _title = value; }

            //}

            public string FolderID

            {

                get { return _uniqueId; }

                set { _uniqueId = value; }

            }

            public string RelativeURL

            {

                get { return _relativeURL; }

                set { _relativeURL = value; }

            }

            public string FolderDirPath

            {

                get { return _fileDirPath; }

                set { _fileDirPath = value; }

            }

            public string FolderType

            {

                get { return _fileType; }

                set { _fileType = value; }

            }

            public string HtmlFileType

            {

                get { return _htmlfileType; }

                set { _htmlfileType = value; }

            }

            public string TypedObject

            {

                get { return _typedObject; }

                set { _typedObject = value; }

            }

            public string FolderSize_KB

            {

                get { return _FileSize_KB; }

                set { _FileSize_KB = value; }

            }

            public string FSObJType

            {

                get { return _FSObJType; }

                set { _FSObJType = value; }

            }

            public string CreatedBy

            {

                get { return _Author; }

                set { _Author = value; }

            }

            public string CreatedByEmail

            {

                get { return _createdByEmail; }

                set

                {

                    _createdByEmail = value;

                }

            }

            public string ModifiedBy

            {

                get { return _ModifiedBy; }

                set { _ModifiedBy = value; }

            }

            public string ModifiedByEmail

            {

                get { return _modifiedByEmail; }

                set { _modifiedByEmail = value; }

            }

            public string CreatedTime

            {

                get { return _CreatedTime; }

                set { _CreatedTime = value; }

            }

            public string ModifiedTime

            {

                get { return _ModifiedTime; }

                set { _ModifiedTime = value; }

            }


            //public string folderRelativePath

            //{

            //    get { return _folderRelativePath; }

            //    set { _folderRelativePath = value; }

            //}

            //public string folder_Eff_Year

            //{

            //    get { return _folder_Eff_Year; }

            //    set { _folder_Eff_Year = value; }

            //}

            //public string folder_UW

            //{

            //    get { return _folder_UW; }

            //    set { _folder_UW = value; }

            //}

            //public string folder_AccountName

            //{

            //    get { return _folder_AccountName; }

            //    set { _folder_AccountName = value; }

            //}

            //public string folder_Category

            //{

            //    get { return _folder_Category; }

            //    set { _folder_Category = value; }

            //}

            //public string folder_SubCategory

            //{

            //    get { return _folder_SubCategory; }

            //    set { _folder_SubCategory = value; }

            //}

            //public string folder_Product

            //{

            //    get { return _folder_Product; }

            //    set { _folder_Product = value; }

            //}

            //public string folder_EffectiveDate

            //{

            //    get { return _folder_EffectiveDate; }

            //    set { _folder_EffectiveDate = value; }

            //}            

        }

        public class SourceFolderStructure

        {            

            private string _folderRelativePath;

            private string _folder_Eff_Year;

            private string _folder_UW;

            private string _folder_LOB;

            private string _folder_AccountName;

            private string _folder_Category;

            private string _folder_SubCategory;

            private string _folder_Product;

            private string _folder_EffectiveDate;

            private string _folder_Broker;            

            private string _folder_Description;            

            private string _folder_EnterpriseKeywords;

            private string _folder_CreatedBy;

            private string _folder_ModifiedBy;

            private string _folder_Created;

            private string _folder_Modified;

            private List<SourceFileStructure> _sourceFileInformation;            

            public string folder_AccountName

            {

                get { return _folder_AccountName; }

                set { _folder_AccountName = value; }

            }

            public string folder_Category

            {

                get { return _folder_Category; }

                set { _folder_Category = value; }

            }

            public string folder_SubCategory

            {

                get { return _folder_SubCategory; }

                set { _folder_SubCategory = value; }

            }

            public string FolderRelativePath

            {

                get { return _folderRelativePath; }

                set { _folderRelativePath = value; }

            }

            public string folder_Description

            {

                get { return _folder_Description; }

                set { _folder_Description = value; }

            }

            public string folder_EnterpriseKeywords

            {

                get { return _folder_EnterpriseKeywords; }

                set { _folder_EnterpriseKeywords = value; }

            }

            public string folder_EffYear

            {

                get { return _folder_Eff_Year; }

                set { _folder_Eff_Year = value; }

            }            

            public string folder_EffectiveDate

            {

                get { return _folder_EffectiveDate; }

                set { _folder_EffectiveDate = value; }

            }

            public string folder_Product

            {

                get { return _folder_Product; }

                set { _folder_Product = value; }

            }

            public string folder_UW

            {

                get { return _folder_UW; }

                set { _folder_UW = value; }

            }

            public string folder_LOB

            {

                get { return _folder_LOB; }

                set { _folder_LOB = value; }

            }                              

            public string folder_Broker

            {

                get { return _folder_Broker; }

                set { _folder_Broker = value; }

            }

            public string folder_Created

            {

                get { return _folder_Created; }

                set { _folder_Created = value; }

            }

            public string folder_Modified

            {

                get { return _folder_Modified; }

                set { _folder_Modified = value; }

            }

            public string folder_CreatedBY

            {

                get { return _folder_CreatedBy; }

                set { _folder_CreatedBy = value; }

            }

            public string folder_ModifiedBy

            {

                get { return _folder_ModifiedBy; }

                set { _folder_ModifiedBy = value; }

            }

            public List<SourceFileStructure> SourceFileInformation

            {

                get { return _sourceFileInformation; }

                set { _sourceFileInformation = value; }

            }

        }

        public class SourceFileStructure

        {

            private string _file_ID;

            private string _file_UniqueID;

            private string _file_Name;

            private string _file_Source_RelativeURL;

            private string _file_target_RelativeURL;

            private string _file_Actual_RelativeURL;

            private string _file_target_ID;

            private string _file_Broker;

            private string _file_Created;            

            private string _file_Description;

            private string _file_EnterpriseKeywords;

            private string _file_Modified;

            private string _file_MRSICategory;

            private string _file_MRSIEffectiveDate;

            private string _file_MRSIEffYear;

            private string _file_MRSILOB;

            private string _file_MRSINANDA;

            private string _file_MRSIProduct;

            private string _file_MRSISubcategory;

            private string _file_MRSIUW;

            private string _file_CreatedBy;

            private string _file_ModifiedBy;


            public string file_ID

            {

                get { return _file_ID; }

                set { _file_ID = value; }

            }

            public string file_UniqueID

            {

                get { return _file_UniqueID; }

                set { _file_UniqueID = value; }

            }

            public string file_Name

            {

                get { return _file_Name; }

                set { _file_Name = value; }

            }

            public string SourcefileRelativeURL

            {

                get { return _file_Source_RelativeURL; }

                set { _file_Source_RelativeURL = value; }

            }

            public string TargetfileRelativeURL

            {

                get { return _file_target_RelativeURL; }

                set { _file_target_RelativeURL = value; }           

            }


            public string file_Actual_RelativeURL

            {

                get { return _file_Actual_RelativeURL; }

                set { _file_Actual_RelativeURL = value; }

            }

            public string TargetfileID

            {

                get { return _file_target_ID; }

                set { _file_target_ID = value; }

            }

            public string file_Description

            {

                get { return _file_Description; }

                set { _file_Description = value; }

            }

            public string file_EnterpriseKeywords

            {

                get { return _file_EnterpriseKeywords; }

                set { _file_EnterpriseKeywords = value; }

            }

            public string file_Modified

            {

                get { return _file_Modified; }

                set { _file_Modified = value; }

            }

            public string file_MRSICategory

            {

                get { return _file_MRSICategory; }

                set { _file_MRSICategory = value; }

            }

            public string file_MRSISubcategory

            {

                get { return _file_MRSISubcategory; }

                set { _file_MRSISubcategory = value; }

            }

            public string file_MRSIEffectiveDate

            {

                get { return _file_MRSIEffectiveDate; }

                set { _file_MRSIEffectiveDate = value; }

            }

            public string file_MRSIEffYear

            {

                get { return _file_MRSIEffYear; }

                set { _file_MRSIEffYear = value; }

            }

            public string file_MRSILOB

            {

                get { return _file_MRSILOB; }

                set { _file_MRSILOB = value; }

            }

            public string file_MRSINANDA

            {

                get { return _file_MRSINANDA; }

                set { _file_MRSINANDA = value; }

            }

            public string file_MRSIProduct

            {

                get { return _file_MRSIProduct; }

                set { _file_MRSIProduct = value; }

            }            

            public string file_MRSIUW

            {

                get { return _file_MRSIUW; }

                set { _file_MRSIUW = value; }

            }

            public string file_Broker

            {

                get { return _file_Broker; }

                set { _file_Broker = value; }

            }

            public string file_Created

            {

                get { return _file_Created; }

                set { _file_Created = value; }

            }


            public string file_CreatedBY

            {

                get { return _file_CreatedBy; }

                set { _file_CreatedBy = value; }

            }

            public string file_ModifiedBy

            {

                get { return _file_ModifiedBy; }

                set { _file_ModifiedBy = value; }

            }

        }

        public class MasterExcelData

        {

            private string _InsuredName;

            private string _SubmissionDate;

            private string _EffectiveDate;

            private string _Status;

            private string _DeclinationReason;

            private string _RiskStatus;

            private string _InsuredState;

            private string _BrokerageName;

            private string _BrokerState;

            private string _Layer;

            private string _Underwriter;

            private string _Notes;

            private string _PolicyNumber;

            private string _EffectiveYear;

            private string _LOB;


            public string InsuredName

            {

                get { return _InsuredName; }

                set { _InsuredName = value; }

            }

            public string SubmissionDate

            {

                get { return _SubmissionDate; }

                set { _SubmissionDate = value; }

            }

            public string EffectiveDate

            {

                get { return _EffectiveDate; }

                set { _EffectiveDate = value; }

            }

            public string InsuredStatus

            {

                get { return _Status; }

                set { _Status = value; }

            }

            public string DeclinationReason

            {

                get { return _DeclinationReason; }

                set { _DeclinationReason = value; }

            }

            public string RiskStatus

            {

                get { return _RiskStatus; }

                set { _RiskStatus = value; }

            }

            public string InsuredState

            {

                get { return _InsuredState; }

                set { _InsuredState = value; }

            }

            public string BrokerageName

            {

                get { return _BrokerageName; }

                set { _BrokerageName = value; }

            }

            public string BrokerState

            {

                get { return _BrokerState; }

                set { _BrokerState = value; }

            }

            public string Layer

            {

                get { return _Layer; }

                set { _Layer = value; }

            }

            public string Underwriter

            {

                get { return _Underwriter; }

                set { _Underwriter = value; }

            }

            public string Notes

            {

                get { return _Notes; }

                set { _Notes = value; }

            }

            public string PolicyNumber

            {

                get { return _PolicyNumber; }

                set { _PolicyNumber = value; }

            }

            public string EffectiveYear

            {

                get { return _EffectiveYear; }

                set { _EffectiveYear = value; }

            }

            public string LOB

            {

                get { return _LOB; }

                set { _LOB = value; }

            }

        }

    }

    public class CommonSiteCloumn

    {        

        public class FileDataTableHeader

        {

            public const string ID = "ID";

            public const string ContentType = "ContentType";

            public const string FileName = "FileName";

            public const string Title = "Title";

            public const string FileID = "FileID";

            public const string FileDirPath = "FileDirPath";

            public const string RelativeURL = "RelativeURL";

            public const string FileType = "FileType";

            public const string HtmlFileType = "HtmlFileType";

            public const string CreatedBy = "CreatedBy";

            public const string CreatedByEmail = "CreatedByEmail";

            public const string CheckedOutByUser = "CheckedOutByUser";

            public const string ModifiedBy = "ModifiedBy";

            public const string ModifiedByEmail = "ModifiedByEmail";

            public const string LastModified = "LastModified";

            public const string CreatedTime = "CreatedTime";

            public const string ModifiedTime = "ModifiedTime";

        }

        public class FolderDataTableHeader

        {

            public const string ID = "ID";

            public const string ContentType = "ContentType";

            public const string FolderName = "FolderName";

            public const string FolderID = "FolderID";

            public const string RelativeURL = "RelativeURL";

            public const string FolderDirPath = "FolderDirPath";

            public const string FolderType = "FolderType";

            public const string HtmlFileType = "HtmlFileType";

            public const string TypedObject = "TypedObject";

            public const string FolderSize_KB = "FolderSize_KB";

            public const string FSObJType = "FSObJType";

            public const string CreatedBy = "CreatedBy";

            public const string CreatedByEmail = "CreatedByEmail";

            public const string ModifiedBy = "ModifiedBy";

            public const string ModifiedByEmail = "ModifiedByEmail";

            public const string CreatedTime = "CreatedTime";

            public const string ModifiedTime = "ModifiedTime";

        }

        public class UnderWritingField

        {

            public const string MRSIEffectiveDate = "MRSI_x002d_Effective_x002d_Date";

            public const string MRSIUW = "MRSI_x002d_UW";


            public const string MRSIProduct = "MRSI_x002d_Product";

            public const string MRSICategory = "MRSI_x002d_Category";

            public const string MRSISubcategory = "MRSI_x002d_Subcategory";

            public const string Broker = "MRSI_x002d_Broker";

            public const string MRSINANDA = "MRSI_x002d_Nanda";

            public const string MRSIEffYear = "MRSI_x002d_Eff_x002d_Year";

            public const string MRSILOB = "MRSI_x002d_LOB";

            public const string CheckoutUser = "CheckoutUser";

        }

        public class LibraryCommonField

        {

            public const string ID = "ID";

            public const string FileLeafRef = "FileLeafRef";

            public const string FSObjType = "FSObjType";

            public const string UniqueId = "UniqueId";

            public const string FileType = "File_x0020_Type";

            public const string FileRef = "FileRef";

            public const string FileDirRef = "FileDirRef";

            public const string CreatedBy = "Author";

            public const string ModifiedBy = "Editor";

            public const string Created = "Created";

            public const string Modified = "Modified";

            public const string FileSize = "File_x0020_Size"; 

            public const string HTMLFileType = "HTML_x0020_File_x0020_Type";

            public const string LastModified = "Last_x0020_Modified";

            public const string CheckoutUser = "CheckoutUser"; 

            public const string ItemChildCount = "ItemChildCount"; 

            public const string FolderChildCount = "FolderChildCount";

            public const string SMTotalFileStreamSize = "SMTotalFileStreamSize";            

        }

        public class MigrationMasterExcelHeader

        {

            public const string InsuredName = "Insured Name";

            public const string Submissiondate = "Submission Date";

            public const string EffDate = "Effective Date";

            public const string Status = "Status";

            public const string RiskStatus = "Risk Status";

            public const string DeclinationStatus = "Declination Reason";

            public const string InsureStatus = "Insured Status";

            public const string InsuredState = "Insured State";

            public const string BrokerageName = "Brokerage Name";

            public const string BrokerState = "Broker State";

            public const string layer = "Layer";

            public const string UnderWriter = "Underwriter";

            public const string notes = "Notes";

            public const string policyNumber = "Policy Number";

            public const string EffYear = "Effective Year";

            public const string lob = "LOB";

            public const string Product = "Product";

        }

        public class AuditTableHeader

        {

            public const string Date = "Date";

            public const string Status = "Status";

            public const string Type = "Type";

            public const string Title = "Title";

            public const string Action = "Action";

            public const string ID = "ID";            

            public const string Sourcesiteaddress = "Source site address";

            public const string Sourcesitename = "Source site name";

            public const string Sourcelisttitle = "Source list title";

            public const string SourcelistID = "Source list ID";

            

            public const string Sourcepath = "Source path";

            public const string SourceID = "Source ID";

            public const string SourceCreatedBy = "Source CreatedBy";

            public const string SourceModifiedBy = "Source ModifiedBy";

            public const string SourceCreatedTime = "Source Created date";

            public const string SourceModifiedTime = "Source Modified date";


            public const string InsuredName = "Insured Name";

            public const string Category = "Category";

            public const string Submissiondate = "Submission Date";

            public const string EffDate = "Effective Date";

            public const string BrokerageName = "Brokerage Name";

            public const string BrokerState = "Broker State";

            public const string layer = "Layer";

            public const string UnderWriter = "Underwriter";

            public const string notes = "Notes";            

            public const string EffYear = "Effective Year";

            public const string lob = "LOB";

            public const string Product = "Product";

           


            public const string Destinationsiteaddress = "Destination site address";

            public const string Destinationsitename = "Destination site name";

            public const string Destinationlisttitle = "Destination list title";

            public const string DestinationlistID = "Destination list ID";

            public const string Destinationpath = "Destination path";

            public const string DestinationID = "Destination ID";

            public const string DestinationCreatedBy = "Destination CreatedBy";

            public const string DestinationModifiedBy = "Destination ModifiedBy";

            public const string DestinationCreatedTime = "Destination Created date";

            public const string DestinationModifiedTime = "Destination Modified date";


            public const string Messages = "Messages";

            public const string Warnings = "Warnings";

            public const string Errors = "Errors";

            public const string Copyoptions = "Copyoptions";

            public const string Details = "Details";

        }


        public class DocumentsetInfoHeader

        {

            public const string ID = "ID";

            public const string DS_ListName = "DS_ListName";

            public const string InsuredName = "InsuredName";

            public const string FolderID = "FolderID";

            public const string RelativeURL = "RelativeURL";

            public const string FolderDirPath = "FolderDirPath";

            public const string FolderType = "FolderType";

            public const string HtmlFileType = "HtmlFileType";

            public const string FolderSize_KB = "FolderSize_KB";

            public const string FolderChildCount = "FolderChildCount";

            public const string ItemChildCount = "ItemChildCount";

            public const string FSObJType = "FSObJType";

            public const string CreatedBy = "CreatedBy";

            public const string CreatedByEmail = "CreatedByEmail";

            public const string ModifiedBy = "ModifiedBy";

            public const string ModifiedByEmail = "ModifiedByEmail";

            public const string CreatedTime = "CreatedTime";

            public const string ModifiedTime = "ModifiedTime";

            public const string DS_MRSI_EffectiveDat = "DS_MRSI_EffectiveDat";

            public const string DS_MRSI_UW = "DS_MRSI_UW";

            public const string DS_RelativePath = "DS_RelativePath";

            public const string DS_MRSI_Product = "DS_MRSI_Product";

            public const string DS_MRSI_Category = "DS_MRSI_Category";

            public const string DS_MRSI_Subcategory = "DS_MRSI_Subcategory";

            public const string DS_Broker = "DS_Broker";

            public const string DS_MRSI_NANDA = "DS_MRSI_NANDA";

            public const string DS_MRSI_EffYear = "DS_MRSI_EffYear";

            public const string DS_MRSI_LOB = "DS_MRSI_LOB";

            public const string DS_CheckoutUser = "DS_CheckoutUser";

        }

    }

    public static class StringUtility

    {

        //if (word.StartsWithAny(new List<string>() { "A", "B", "C" })) 

        //{

        //    // do something

        //}

        public static string[] Split(this string input, string separator)

        {

            var splitRegex = new Regex(

                Regex.Escape(separator),

                RegexOptions.Singleline | RegexOptions.Compiled

                );


            return splitRegex.Split(input);

        }


        public static bool StartWith(this string input,string substring)

        {

            bool isStart = false;

            input = input.Trim();

            substring = substring.Trim();

            isStart=input.StartsWith(substring);

            return isStart;

        }


        public static bool StartsWithAny(this string source, IEnumerable<string> strings)

        {

            foreach (var valueToCheck in strings)

            {

                if (source.StartsWith(valueToCheck))

                {

                    return true;

                }

            }


            return false;

        }

        public static bool StartsWithAny(this string source, IEnumerable<string> strings, out string startsWithValue)

        {

            startsWithValue = null;


            foreach (var valueToCheck in strings)

            {

                if (source.StartsWith(valueToCheck))

                {

                    startsWithValue = valueToCheck;

                    return true;

                }

            }


            return false;

        }


        public static bool IsDateTime(string text)

        {

            DateTime dateTime;

            bool isdateTime = false;

            if (DateTime.TryParse(text, out dateTime))

            {

                isdateTime = true;

            }

            return isdateTime;

        }

        public static string RemoveSpecialChars(string str)

        {

            // Create  a string array and add the special characters you want to remove

            string[] chars = new string[] { ",", ".", "/", "!", "@", "#", "$", "%", "^", "&", "*", "'", "\"", ";", "_", "(", ")", ":", "|", "[", "]" };

            //Iterate the number of times based on the String array length.

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

            {

                if (str.Contains(chars[i]))

                {

                    str = str.Replace(chars[i], "");

                }

            }

            return str;

        }


        public static string RemoveSpecialCharsUseRegex(string stringwithSpclCharac)

        {

            var StringWithoutSpclCharac = Regex.Replace(stringwithSpclCharac, @"[^0-9a-zA-Z\._]", "");

            return StringWithoutSpclCharac;

        }


        //StringBuilder

        public static string RemoveSpecialCharactersSB(string str)

        {

            StringBuilder sb = new StringBuilder();

            foreach (char c in str)

            {

                if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '.' || c == '_')

                {

                    sb.Append(c);

                }

            }

            return sb.ToString();

        }

        public static string ReplaceString(this string source, string oldValue, string newValue)

        {

            if (source != null)

            {

                var sourceArr = source.Split(new[] { oldValue }, StringSplitOptions.None);


                var result = new StringBuilder();


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

                {

                    result.Append(sourceArr[i]);


                    if (i + 1 != sourceArr.Length)

                    {

                        result.Append(newValue);

                    }

                }


                return result.ToString();

            }

            return null;

        }

        public static string ReplaceStringLinq(this string source, string oldValue, string newValue)

        {

            if (source != null)

            {

                var sourceArr = source.Split(new[] { oldValue }, StringSplitOptions.None);

                var start = sourceArr.Take(1);

                var end =

                from originalString in sourceArr.Skip(1)

                from newString in new[] { newValue, originalString }

                select newString;

                var result = String.Join("", start.Concat(end));

                return result;

            }


            return null;

        }

    }






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




internal class SPFileMigrationExtension

    {

        

        public static async Task CopyAllFiletoDocumentSetWithMetaData(ClientContext SourceContext, ClientContext DestinationContext, List<Common.SourceFolderStructure> sourceFolderStructures

            ,string SourceListName, string TargetListName, string docSetContentTypeName)

        {

            System.Data.DataTable AuditdataTable = new System.Data.DataTable(typeof(CommonSiteCloumn.AuditTableHeader).Name);

            try

            {

                //IList<Task<Folder>> dsDestinationfolders = new List<Task<Folder>>();

                //IList<Task> Destinationtasks = new List<Task>();

                #region make structure of audit data table                

                //Get all the properties by using reflection   

                var declaredFields = typeof(CommonSiteCloumn.AuditTableHeader).GetFields(BindingFlags.Public | BindingFlags.Static |

                BindingFlags.FlattenHierarchy).Where(fi => fi.IsLiteral && !fi.IsInitOnly).Select(x => (string)x.GetRawConstantValue()).ToList();

                //PropertyInfo[] Props = typeof(CommonSiteCloumn.AuditTableHeader).GetProperties(BindingFlags.Public | BindingFlags.Instance);

                foreach (var prop in declaredFields)

                {

                    //Setting column names as Property names                      

                    AuditdataTable.Columns.Add(prop);

                }

                #endregion

                List SourceList = SourceContext.Web.Lists.GetByTitle(SourceListName);

                SourceContext.Load(SourceList);

                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();


                List TargetList = DestinationContext.Web.Lists.GetByTitle(TargetListName);

                DestinationContext.Load(TargetList);

                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);


                //var dsSourceContentType = TargetList.GetContentTypeByName(docSetContentTypeName);

                //var matchDSSourceCTID = TargetList.BestMatchContentTypeId(dsSourceContentType.Id.StringValue);


                var allSourceFiles = sourceFolderStructures.Select(li => li.SourceFileInformation).ToList();

                IList<Task> oSourceTask = new List<Task>();

                List<Microsoft.SharePoint.Client.File> oSourceFiles = new List<Microsoft.SharePoint.Client.File>();

                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 filecollection = listItems.Cast<ListItem>().Where(li => li.FileSystemObjectType == FileSystemObjectType.File).Select(li => li).ToList();

                    odsSourceListItems.AddRange(filecollection);

                    Console.SetCursorPosition(left, top);

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

                });

                left = Console.CursorLeft;

                top = Console.CursorTop;

                

                foreach (var sourceFileCollection in allSourceFiles)

                {

                    foreach(var sourceFile in sourceFileCollection)

                    {

                        string fileserverRelativeURL = sourceFile.SourcefileRelativeURL;

                        var olistItem = odsSourceListItems.Where(f => f.FieldValues[CommonSiteCloumn.LibraryCommonField.FileRef].ToString().Contains(fileserverRelativeURL)).FirstOrDefault();

                        if (olistItem != null)

                        {

                            var spoFile = olistItem.File;

                            oSourceFiles.Add(spoFile);

                            SourceContext.Load(spoFile, f => f, f => f.ListItemAllFields, f => f.CheckedOutByUser);

                            oSourceTask.Add(SourceContext.ExecuteQueryAsync());

                            Console.SetCursorPosition(left, top);

                            Console.WriteLine(string.Format("Source Files 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 sourceFolderStructures)

                    {

                        DataRow AuditdataRow = null;

                        try

                        {

                            if (item != null)

                            {

                                dsCount++;

                                string DS = item.folder_AccountName;

                                string DSRelativeUrl = item.FolderRelativePath;

                                

                                AuditdataRow=AuditdataTable.NewRow();

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Date] = DateTime.Now.ToString("g");

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Type] = "Folder";

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Title] = item.folder_AccountName;

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Action] = "Copy";

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Sourcesiteaddress] = SourceContext.Web.Url;

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Sourcesitename] = SourceContext.Web.Title;

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Sourcelisttitle] = SourceList.Title;

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.SourcelistID] = Convert.ToString(SourceList.Id);

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Sourcepath] = Convert.ToString(item.FolderRelativePath);

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.SourceCreatedBy] = Convert.ToString(item.folder_CreatedBY);

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.SourceModifiedBy] = Convert.ToString(item.folder_ModifiedBy);

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.SourceCreatedTime] = Convert.ToString(item.folder_Created);

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.InsuredName] = Convert.ToString(item.folder_AccountName);                                

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.EffDate] = Convert.ToString(item.folder_EffectiveDate);

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.BrokerageName] = Convert.ToString(item.folder_Broker);                                                                

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.UnderWriter] = Convert.ToString(item.folder_UW);

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.EffYear] = Convert.ToString(item.folder_EffYear);

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.lob] = Convert.ToString(item.folder_LOB);

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Product] = Convert.ToString(item.folder_Product);

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Category] = Convert.ToString(item.folder_Category);

                                //Insured Name    Submission Date Effective Date  Brokerage Name  Broker State    Layer Underwriter Notes Effective Year LOB


                                Log.Instance.Debug("SRNO: {0} Document Set Name: {1} and DocSetURL: {2}", dsCount.ToString(), DS, DSRelativeUrl);

                                var newTargetDSFolder = await GetDocumentSet(DestinationContext, TargetList, matchDSDestinationCTID, TargetList.Fields, item, DS);

                                if (newTargetDSFolder!=null)

                                {

                                    //Destination ID Destination CreatedBy Destination ModifiedBy Destination Created date Destination Modified date


                                    AuditdataRow[CommonSiteCloumn.AuditTableHeader.Destinationsiteaddress]=DestinationContext.Web.Url;

                                    AuditdataRow[CommonSiteCloumn.AuditTableHeader.Destinationsitename]=DestinationContext.Web.Title;

                                    AuditdataRow[CommonSiteCloumn.AuditTableHeader.Destinationlisttitle]=TargetList.Title;

                                    AuditdataRow[CommonSiteCloumn.AuditTableHeader.DestinationlistID]= Convert.ToString(TargetList.Id);

                                    AuditdataRow[CommonSiteCloumn.AuditTableHeader.Destinationpath] = newTargetDSFolder.ServerRelativeUrl;

                                    AuditdataRow[CommonSiteCloumn.AuditTableHeader.DestinationID] = newTargetDSFolder.ListItemAllFields.Id.ToString();

                                    AuditdataRow[CommonSiteCloumn.AuditTableHeader.DestinationCreatedBy] = Convert.ToString(((FieldUserValue)newTargetDSFolder.ListItemAllFields.FieldValues[CommonSiteCloumn.LibraryCommonField.CreatedBy]).Email);

                                    AuditdataRow[CommonSiteCloumn.AuditTableHeader.DestinationCreatedTime] = ((DateTime)newTargetDSFolder.ListItemAllFields.FieldValues[CommonSiteCloumn.LibraryCommonField.Created]).ToString("MM/dd/yyyy");

                                    AuditdataRow[CommonSiteCloumn.AuditTableHeader.DestinationModifiedTime] = ((DateTime)newTargetDSFolder.ListItemAllFields.FieldValues[CommonSiteCloumn.LibraryCommonField.Modified]).ToString("MM/dd/yyyy");

                                    AuditdataRow[CommonSiteCloumn.AuditTableHeader.DestinationModifiedBy] = Convert.ToString(((FieldUserValue)newTargetDSFolder.ListItemAllFields.FieldValues[CommonSiteCloumn.LibraryCommonField.ModifiedBy]).Email);


                                    AuditdataRow[CommonSiteCloumn.AuditTableHeader.Status] = "Success";

                                    AuditdataRow[CommonSiteCloumn.AuditTableHeader.Details] = "Copied successfully.";

                                    AuditdataTable.Rows.Add(AuditdataRow);

                                    if (item.SourceFileInformation != null)

                                    {

                                        //FolderExtensions.updateDocumentSetMetaData(SourceContext, DestinationContext, item, newTargetDSFolder, SourceList.Fields, TargetList.Fields);

                                        var targetDSFileCollection = newTargetDSFolder.Files.Cast<Microsoft.SharePoint.Client.File>().ToList();

                                        if (item.SourceFileInformation.Count > 0)

                                        {

                                            List<Microsoft.SharePoint.Client.File> dictionaryFiles = new List<Microsoft.SharePoint.Client.File>();

                                            foreach (var sourcefile in item.SourceFileInformation)

                                            {

                                                try

                                                {

                                                    

                                                    string fileName = Convert.ToString(sourcefile.file_Name);

                                                    string fileRelativeUrl = Convert.ToString(sourcefile.SourcefileRelativeURL);                                                    

                                                    //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();

                                                    //fileName = StringUtility.RemoveSpecialCharsUseRegex(sourcefile.file_Name);

                                                    if (isFileAlready != null)

                                                    {                                                        

                                                        string timestamp = string.Format("{0:yyyy-MM-dd_HH-mm-ss-fff}", DateTime.Now);

                                                        int indexExtension=fileName.LastIndexOf('.')-1;

                                                        string[] array = fileName.Split(".");

                                                        string extension = fileName.Split(".")[array.Length - 1];

                                                        if (indexExtension > -1)

                                                        {

                                                            fileName = fileName.Substring(0, indexExtension);

                                                        }

                                                        fileName = string.Format("{0}_{1}.{2}", fileName, timestamp, extension);

                                                        isFileAlready = null;

                                                    }

                                                    if (isFileAlready == null)

                                                    {

                                                        //var TargetNewFileURL = StringUtility.ReplaceString(fileRelativeUrl, DSRelativeUrl, TargetList.RootFolder.ServerRelativeUrl + "/" + newTargetDSFolder.Name);

                                                        var TargetNewFileURL = sourcefile.TargetfileRelativeURL.Trim();

                                                        var sourceSPfile=oSourceFiles.FirstOrDefault(f=>f.ServerRelativeUrl == fileRelativeUrl);

                                                        if (sourceSPfile != null)

                                                        {

                                                            var fileStreamResult = sourceSPfile.OpenBinaryStream();

                                                            SourceContext.Load(sourceSPfile);

                                                            SourceContext.ExecuteQuery();

                                                            MemoryStream datastream = new MemoryStream();

                                                            await fileStreamResult.Value.CopyToAsync(datastream);                                                            

                                                            var newFile = await UploadFiletoSharePoint(DestinationContext, TargetList, newTargetDSFolder, datastream, fileName);

                                                            if (newFile != null)

                                                            {

                                                                fileCount++;

                                                                dictionaryFiles.Add(newFile);

                                                                if (newFile.IsObjectPropertyInstantiated("ServerRelativeUrl"))

                                                                {

                                                                    sourcefile.file_Actual_RelativeURL = newFile.ServerRelativeUrl;

                                                                }

                                                                else

                                                                {

                                                                    sourcefile.file_Actual_RelativeURL = Convert.ToString(newFile.ListItemAllFields.FieldValues[CommonSiteCloumn.LibraryCommonField.FileRef]);

                                                                }

                                                                Log.Instance.Info("SRNO '{0}' Copy file '{1}' to '{2}'", fileCount.ToString(), fileRelativeUrl, newFile.ServerRelativeUrl);                                                                

                                                                AuditdataRow = AuditdataTable.NewRow();

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Date] = DateTime.Now.ToString("g");

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Type] = "File";

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Title] = sourcefile.file_Name;

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Action] = "Copy";

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.SourceID] = sourcefile.file_ID;

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Sourcesiteaddress] = SourceContext.Web.Url;

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Sourcesitename] = SourceContext.Web.Title;

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Sourcelisttitle] = SourceList.Title;

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.SourcelistID] = SourceList.Id.ToString();

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Sourcepath] = Convert.ToString(sourcefile.SourcefileRelativeURL);

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.SourceCreatedBy] = Convert.ToString(sourcefile.file_CreatedBY);

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.SourceModifiedBy] = Convert.ToString(sourcefile.file_ModifiedBy);

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.SourceCreatedTime] = Convert.ToString(sourcefile.file_Created);

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.SourceModifiedTime] = Convert.ToString(sourcefile.file_Modified);

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.InsuredName] = Convert.ToString(item.folder_AccountName);

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Category] = Convert.ToString(sourcefile.file_MRSICategory);

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.EffDate] = Convert.ToString(sourcefile.file_MRSIEffectiveDate);

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.BrokerageName] = Convert.ToString(sourcefile.file_Broker);

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.UnderWriter] = Convert.ToString(sourcefile.file_MRSIUW);

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.EffYear] = Convert.ToString(sourcefile.file_MRSIEffYear);

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.lob] = Convert.ToString(sourcefile.file_MRSILOB);

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Product] = Convert.ToString(sourcefile.file_MRSIProduct);




                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Destinationsiteaddress] = DestinationContext.Web.Url;

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Destinationsitename] = DestinationContext.Web.Title;

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Destinationlisttitle] = TargetList.Title;

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.DestinationlistID] = Convert.ToString(TargetList.Id);

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Destinationpath] = Convert.ToString(newFile.ListItemAllFields.FieldValues[CommonSiteCloumn.LibraryCommonField.FileRef]);

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.DestinationID] = Convert.ToString(newFile.ListItemAllFields.Id);                                                                

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.DestinationCreatedBy] = Convert.ToString(((FieldUserValue)newFile.ListItemAllFields.FieldValues[CommonSiteCloumn.LibraryCommonField.CreatedBy]).Email);

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.DestinationCreatedTime] = ((DateTime)newFile.ListItemAllFields.FieldValues[CommonSiteCloumn.LibraryCommonField.Created]).ToString("MM/dd/yyyy");

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.DestinationModifiedTime] = ((DateTime)newFile.ListItemAllFields.FieldValues[CommonSiteCloumn.LibraryCommonField.Modified]).ToString("MM/dd/yyyy");

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.DestinationModifiedBy] = Convert.ToString(((FieldUserValue)newFile.ListItemAllFields.FieldValues[CommonSiteCloumn.LibraryCommonField.ModifiedBy]).Email);


                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Status] = "Success";

                                                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Details] = "Copied successfully.";

                                                                AuditdataTable.Rows.Add(AuditdataRow);

                                                                //await updateFileMetaData(SourceContext, DestinationContext, sourcefile, newFile, SourceList.Fields, TargetList.Fields);

                                                            }

                                                        }

                                                    }

                                                }

                                                catch (Exception ex)

                                                {

                                                    Console.WriteLine("File Error: {0}", ex.Message);

                                                    if (AuditdataRow != null)

                                                    {

                                                        AuditdataRow[CommonSiteCloumn.AuditTableHeader.Status] = "Error";

                                                        AuditdataRow[CommonSiteCloumn.AuditTableHeader.Messages] = ex.Message;

                                                        AuditdataRow[CommonSiteCloumn.AuditTableHeader.Details] = string.Format("File Error: {0}\n{1}", ex.Message, ex.StackTrace);

                                                        AuditdataTable.Rows.Add(AuditdataRow);

                                                    }

                                                }

                                            }

                                            if (dictionaryFiles.Count() > 0)

                                            {                                                

                                                await updateMetaDataOfFiles(DestinationContext, TargetList, dictionaryFiles, TargetList.Fields, item.SourceFileInformation);

                                                Log.Instance.Trace("'{0}' Done! to update Copied Files of meta data.", item.folder_AccountName);

                                            }

                                        }

                                    }

                                }

                                else

                                {

                                    string TargetRootFolderRelPath = TargetList.RootFolder.ServerRelativeUrl;

                                    string TargetdocSetRelPath = string.Format("{0}/{1}", TargetRootFolderRelPath, item.folder_AccountName);

                                    if (AuditdataRow != null)

                                    {

                                        AuditdataRow[CommonSiteCloumn.AuditTableHeader.Destinationsiteaddress] = DestinationContext.Web.Url;

                                        AuditdataRow[CommonSiteCloumn.AuditTableHeader.Destinationsitename] = DestinationContext.Web.Title;

                                        AuditdataRow[CommonSiteCloumn.AuditTableHeader.Destinationlisttitle] = TargetList.Title;

                                        AuditdataRow[CommonSiteCloumn.AuditTableHeader.DestinationlistID] = Convert.ToString(TargetList.Id);

                                        AuditdataRow[CommonSiteCloumn.AuditTableHeader.Destinationpath] = TargetdocSetRelPath;

                                        AuditdataRow[CommonSiteCloumn.AuditTableHeader.Messages] = "Insured name does not exist in Underwriting Files.";

                                        AuditdataRow[CommonSiteCloumn.AuditTableHeader.Details] = "Not Copied.";

                                        AuditdataRow[CommonSiteCloumn.AuditTableHeader.Status] = "Pending";

                                        AuditdataTable.Rows.Add(AuditdataRow);

                                    }

                                }

                            }

                        }

                        catch (Exception ex)

                        {

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

                            Log.Instance.Error(exString);

                            if (AuditdataRow != null)

                            {

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Status] = "Error";

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Messages] = ex.Message;

                                AuditdataRow[CommonSiteCloumn.AuditTableHeader.Details] = exString;

                                AuditdataTable.Rows.Add(AuditdataRow);

                            }

                        }

                    }                   

                }

            }

            catch (Exception ex)

            {

            }

            finally

            {

                if (AuditdataTable != null)

                {

                    if (AuditdataTable.Rows.Count > 0)

                    {

                        Console.WriteLine("\n");

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

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

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

                        try

                        {                            

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

                            ExcelManager.ToCSV(AuditdataTable, csvFilePath);

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

                        }

                        catch (Exception ex)

                        {

                            string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                            Log.Instance.Error(exString);

                        }

                    }

                }

            }

        }


        private static async Task<Microsoft.SharePoint.Client.Folder> GetDocumentSet(ClientContext destinationContext, List targetList, ContentTypeId matchDSDestinationCTID, 

            FieldCollection TargetFieldsColl, Common.SourceFolderStructure sourceFolderStructure, string docSetName)

        {

            Microsoft.SharePoint.Client.Folder docSetFolder = null;

            try

            {

                //Make Document Set path using Target RootFolder Path

                string TargetRootFolderRelPath = targetList.RootFolder.ServerRelativeUrl;

                string TargetdocSetRelPath = string.Format("{0}/{1}", TargetRootFolderRelPath, docSetName);

                bool isDocSetExist = DocumentSetExists(destinationContext, targetList, docSetName);

                if (isDocSetExist)

                {

                    docSetFolder = destinationContext.Web.GetFolderByServerRelativeUrl(TargetdocSetRelPath);

                    destinationContext.Load(docSetFolder, f => f, f => f.ListItemAllFields, f => f.ListItemAllFields.ContentType, f => f.Files, f => f.Files.Include(i => i, i => i.ListItemAllFields));

                    await destinationContext.ExecuteQueryAsync();

                    if (docSetFolder != null)

                    {


                    }

                }

                else

                {

                    docSetFolder = await DocumentSetExtension.createNewDocumentSet(destinationContext, targetList, matchDSDestinationCTID, docSetName);                    

                    bool isUpdateMetadata=await updatedocumentSetMetaData(destinationContext, TargetFieldsColl, docSetFolder, sourceFolderStructure);

                    await GetDocumentSet(destinationContext, targetList, matchDSDestinationCTID, TargetFieldsColl, sourceFolderStructure, docSetName);

                }

            }

            catch (Exception ex)

            {

            }

            return docSetFolder;

        }


        private static async Task<bool> updatedocumentSetMetaData(ClientContext TargetCtx,FieldCollection fieldCollection, Folder documentSet, Common.SourceFolderStructure sourceFolderStructure)

        {

            bool isDocMetaDataUpdated = false;

            //Get all the properties by using reflection   

            PropertyInfo[] Props = typeof(Common.SourceFolderStructure).GetProperties(BindingFlags.Public | BindingFlags.Instance);            

            ListItem DS_TargetItem = documentSet.ListItemAllFields;


            //Set Metadata values from the source                        

            foreach (PropertyInfo prop in Props)

            {

                //Setting column names as Property names  

                //dataTable.Columns.Add(prop.Name);

                Field field = getSPOField(fieldCollection, prop.Name);

                if (field != null)

                {

                    string srcFieldName = field.Title;

                    string srcFieldInternalName = field.InternalName;

                    string type = field.GetType().FullName;

                    if (field.Title == "Enterprise Keywords")

                    {

                        continue;

                    }

                    if (!prop.Name.Equals("SourceFileInformation",StringComparison.OrdinalIgnoreCase))

                    {

                        if (DS_TargetItem.FieldValues.ContainsKey(srcFieldInternalName))

                        {

                            var values = prop.GetValue(sourceFolderStructure, null);

                            if (srcFieldName.Equals("MRSI-UW",StringComparison.OrdinalIgnoreCase))

                            {

                                ResourceManager resourceManager = new ResourceManager("Munichre.ES.Migration.MRSIUWResource", Assembly.GetExecutingAssembly());

                                string MRSIUWEmail = resourceManager.GetString(values.ToString(), CultureInfo.CurrentCulture);

                                values = MRSIUWEmail;

                            }

                            if (type == "Microsoft.SharePoint.Client.FieldLookup")

                            {

                                //dr[obj.Key] = ((FieldLookupValue)obj.Value).LookupValue;

                            }

                            else if (type == "Microsoft.SharePoint.Client.FieldUser")

                            {

                                if (values != null)

                                {

                                    var userValue = TargetCtx.Web.EnsureUser(values.ToString());

                                    DS_TargetItem[srcFieldInternalName] = userValue;

                                }

                            }

                            else if (type == "Microsoft.SharePoint.Client.FieldUser[]")

                            {

                                //FieldUserValue[] multValue = (FieldUserValue[])obj.Value;

                                //foreach (FieldUserValue fieldUserValue in multValue)

                                //{

                                //    dr[obj.Key] += (fieldUserValue).LookupValue;

                                //}

                            }

                            else if (type == "Microsoft.SharePoint.Client.FieldDateTime")

                            {

                                if (values != null)

                                {

                                    DateTime dateTime = DateTime.Parse(values.ToString());

                                    if (dateTime != null)

                                    {

                                        DS_TargetItem[srcFieldInternalName] = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);

                                    }

                                }

                            }

                            else

                            {

                                if(values != null)

                                    DS_TargetItem[srcFieldInternalName] = values;

                            }

                        }                        

                    }                   

                }

            }

            try

            {

                if (!string.IsNullOrEmpty(sourceFolderStructure.folder_CreatedBY))

                {

                    var Author = TargetCtx.Web.EnsureUser(sourceFolderStructure.folder_CreatedBY);

                    DS_TargetItem["Author"] = Author;

                }

                if (!string.IsNullOrEmpty(sourceFolderStructure.folder_ModifiedBy))

                {

                    var Editor = TargetCtx.Web.EnsureUser(sourceFolderStructure.folder_ModifiedBy);                    

                    if (sourceFolderStructure.folder_ModifiedBy.Equals("SharePoint App", StringComparison.OrdinalIgnoreCase))

                    {

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

                    }

                    DS_TargetItem["Editor"] = Editor;

                }

                if (!string.IsNullOrEmpty(sourceFolderStructure.folder_Created))

                {

                    DateTime CreatedateTime = DateTime.Parse(sourceFolderStructure.folder_Created);                    

                    if (CreatedateTime != null)

                    {

                        DS_TargetItem["Created"] = DateTime.SpecifyKind(CreatedateTime, DateTimeKind.Utc);

                    }                    

                }

                if (!string.IsNullOrEmpty(sourceFolderStructure.folder_Modified))

                {

                    DateTime ModifieddateTime = DateTime.Parse(sourceFolderStructure.folder_Modified);

                    if (ModifieddateTime != null)

                    {

                        DS_TargetItem["Modified"] = DateTime.SpecifyKind(ModifieddateTime, DateTimeKind.Utc);

                    }

                }

                DS_TargetItem.Update();

                await TargetCtx.ExecuteQueryAsync();

                if (!string.IsNullOrEmpty(sourceFolderStructure.folder_EnterpriseKeywords))

                {

                    string[] keywords = sourceFolderStructure.folder_EnterpriseKeywords.Split(";");

                    KeywordsManager.SetTaxKeywordValue(DS_TargetItem, keywords);

                }

                isDocMetaDataUpdated = true;

            }

            catch (Exception ex)

            {

                string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                Log.Instance.Warn(exString);

                isDocMetaDataUpdated = false;

            }

            if(isDocMetaDataUpdated)

                Log.Instance.Info(string.Format("Account '{0}' meta data has been updated successfully.", DS_TargetItem[CommonSiteCloumn.LibraryCommonField.FileLeafRef].ToString()));

            return isDocMetaDataUpdated;

        }


        private static async Task updateMetaDataOfFiles(ClientContext clientContext,List Library,List<File> files,FieldCollection fieldCollection, List<Common.SourceFileStructure> sourceFiles)

        {            

            try

            {

                //Get all the properties by using reflection   

                PropertyInfo[] Props = typeof(Common.SourceFileStructure).GetProperties(BindingFlags.Public | BindingFlags.Instance);

                var listItems=files.Select(f=>f.ListItemAllFields).ToList();

                //Set Metadata values from the source file                        

                int batchExecute = 0;

                listItems.ForEach(async li =>

                {

                    try

                    {

                        string fileRelativeURL = li[CommonSiteCloumn.LibraryCommonField.FileRef].ToString();

                        string fileID = li[CommonSiteCloumn.LibraryCommonField.ID].ToString();

                        ListItem TargetItem = li;

                        if (sourceFiles.Any(sf => sf.file_Actual_RelativeURL.Contains(fileRelativeURL)))

                        {

                            var sourceFile = sourceFiles.FirstOrDefault(sf => sf.file_Actual_RelativeURL.Contains(fileRelativeURL));

                            if (sourceFile != null)

                            {

                                foreach (PropertyInfo prop in Props)

                                {

                                    //Setting column names as Property names  

                                    //dataTable.Columns.Add(prop.Name);

                                    Field field = getSPOField(fieldCollection, prop.Name);

                                    try

                                    {                                        

                                        if (field != null)

                                        {

                                            string srcFieldName = field.Title;

                                            string srcFieldInternalName = field.InternalName;

                                            string type = field.GetType().FullName;

                                            if (field.Title == "Enterprise Keywords")

                                            {

                                                continue;

                                            }

                                            if (TargetItem.FieldValues.ContainsKey(srcFieldInternalName))

                                            {

                                                var values = prop.GetValue(sourceFile, null);

                                                if (type == "Microsoft.SharePoint.Client.FieldLookup")

                                                {

                                                    //dr[obj.Key] = ((FieldLookupValue)obj.Value).LookupValue;

                                                }

                                                else if (type == "Microsoft.SharePoint.Client.FieldUser")

                                                {

                                                    if (values != null)

                                                    {

                                                        var userValue = clientContext.Web.EnsureUser(values.ToString());

                                                        TargetItem[srcFieldInternalName] = userValue;

                                                    }

                                                }

                                                else if (type == "Microsoft.SharePoint.Client.FieldUser[]")

                                                {

                                                    //FieldUserValue[] multValue = (FieldUserValue[])obj.Value;

                                                    //foreach (FieldUserValue fieldUserValue in multValue)

                                                    //{

                                                    //    dr[obj.Key] += (fieldUserValue).LookupValue;

                                                    //}

                                                }

                                                else if (type == "Microsoft.SharePoint.Client.FieldDateTime")

                                                {

                                                    if (values != null)

                                                    {

                                                        DateTime dateTime = DateTime.Parse(values.ToString());

                                                        if (dateTime != null)

                                                        {

                                                            TargetItem[srcFieldInternalName] = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);

                                                        }

                                                    }

                                                }

                                                else

                                                {

                                                    if (values != null)

                                                        TargetItem[srcFieldInternalName] = values;

                                                }

                                            }

                                        }

                                    }

                                    catch (Exception ex)

                                    {

                                        string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                                        Log.Instance.Error(exString);

                                    }                                    

                                }

                                if (!string.IsNullOrEmpty(sourceFile.file_CreatedBY))

                                {

                                    var Author = clientContext.Web.EnsureUser(sourceFile.file_CreatedBY);

                                    TargetItem["Author"] = Author;

                                }

                                if (!string.IsNullOrEmpty(sourceFile.file_ModifiedBy))

                                {                                    

                                    var Editor = clientContext.Web.EnsureUser(sourceFile.file_ModifiedBy);

                                    if(sourceFile.file_ModifiedBy.Equals("SharePoint App", StringComparison.OrdinalIgnoreCase))

                                    {

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

                                    }                                    

                                    TargetItem["Editor"] = Editor;

                                }

                                if (!string.IsNullOrEmpty(sourceFile.file_Created))

                                {

                                    DateTime CreatedateTime = DateTime.Parse(sourceFile.file_Created);

                                    if (CreatedateTime != null)

                                    {

                                        TargetItem["Created"] = DateTime.SpecifyKind(CreatedateTime, DateTimeKind.Utc);

                                    }

                                }

                                if (!string.IsNullOrEmpty(sourceFile.file_Modified))

                                {

                                    DateTime ModifieddateTime = DateTime.Parse(sourceFile.file_Modified);

                                    if (ModifieddateTime != null)

                                    {

                                        TargetItem["Modified"] = DateTime.SpecifyKind(ModifieddateTime, DateTimeKind.Utc);

                                    }

                                }

                                batchExecute = batchExecute + 1;

                                TargetItem.Update();

                                if (batchExecute > 10)

                                {

                                    await clientContext.ExecuteQueryAsync();

                                    batchExecute = 0;

                                }

                            }

                        }

                    }                    

                    catch (Exception ex)

                    {

                        string exString = ExceptionExtensions.GetExceptionFootprints(ex);

                        Log.Instance.Warn(exString);

                    }                    

                });

                await clientContext.ExecuteQueryAsync();

                listItems.ForEach(li =>

                {

                    string fileRelativeURL = li[CommonSiteCloumn.LibraryCommonField.FileRef].ToString();

                    string fileID = li[CommonSiteCloumn.LibraryCommonField.ID].ToString();

                    ListItem TargetItem = li;

                    if (sourceFiles.Any(sf => sf.file_Actual_RelativeURL.Contains(fileRelativeURL)))

                    {

                        var sourceFile = sourceFiles.FirstOrDefault(sf => sf.file_Actual_RelativeURL.Contains(fileRelativeURL));

                        if (sourceFile != null)

                        {

                            if(sourceFile.file_EnterpriseKeywords != null)

                            {

                                if(sourceFile.file_EnterpriseKeywords.Length > 0)

                                {

                                    string[] keywords = sourceFile.file_EnterpriseKeywords.Split(";");

                                    KeywordsManager.SetTaxKeywordValue(li, keywords);

                                }

                            }

                        }

                    }                    

                });

            }

            catch (Exception ex)

            {

            }

        }


        private static async Task<Microsoft.SharePoint.Client.File> UploadFiletoSharePoint(ClientContext CContext, List DocumentLibrary, Folder Targetfolder, 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 = Targetfolder.Files.Add(newFile);


            //CContext.Load(DocumentLibrary);

            await CContext.ExecuteQueryAsync();

            CContext.Load(uploadFile, f => f, f => f.ListItemAllFields);

            CContext.ExecuteQuery();

            

            //Log.Instance.Debug("Total number of Files copied. Count: " + numberofFileCopie.ToString());

            return uploadFile;

        }

        private static Microsoft.SharePoint.Client.Field getSPOField(FieldCollection fields,string propertyName)

        {

            ResourceManager resourceManager = new ResourceManager("Munichre.ES.Migration.ConfigurationResource", Assembly.GetExecutingAssembly());

            string internalName = string.Empty;

            string fieldDisplayName = resourceManager.GetString(propertyName, CultureInfo.CurrentCulture);

            Field SPOfield = fields.Cast<Microsoft.SharePoint.Client.Field>().FirstOrDefault(f => f.Title == fieldDisplayName);

            if (SPOfield != null)

            {

                internalName = SPOfield.InternalName;

                string FieldType=SPOfield.GetType().Name;

            }

            return SPOfield;

        }



        #region CHECK WETHER FOLDER OR FILE EXIST IN SHAREPOINT LIBRARY 

        private static bool DocumentSetExists(ClientContext context, List list, string docSetName)

        {

            string url = list.RootFolder.ServerRelativeUrl + "/" + docSetName;

            return FolderExists(context, url);

        }

        private static bool FolderExists(ClientContext context, List list, string folderName)

        {

            string url = list.RootFolder.ServerRelativeUrl + "/" + folderName;

            return FolderExists(context, url);

        }


        private static bool FolderExists(ClientContext context, Folder currentListFolder, string folderName)

        {

            string url = currentListFolder.ServerRelativeUrl + "/" + folderName;

            return FolderExists(context, url);

        }


        private static bool FolderExists(ClientContext context, string url)

        {

            var folder = context.Web.GetFolderByServerRelativeUrl(url);

            context.Load(folder, f => f.Exists);

            try

            {

                context.ExecuteQuery();


                if (folder.Exists)

                {

                    return true;

                }

                return false;

            }

            catch (ServerUnauthorizedAccessException uae)

            {

                Log.Instance.Warn($"You are not allowed to access this folder");

                throw;

            }

            catch (Exception ex)

            {

                //Log.Instance.Error($"Could not find folder {url}");

                return false;

            }

        }


        private static bool FileExists(ClientContext context, List list, string fileName)

        {

            string url = list.RootFolder.ServerRelativeUrl + "/" + fileName;

            return FileExists(context, url);

        }


        private static bool FileExists(ClientContext context, Folder currentListFolder, string fileName)

        {

            string url = currentListFolder.ServerRelativeUrl + "/" + fileName;

            return FileExists(context, url);

        }


        private static bool FileExists(ClientContext context, string url)

        {

            var file = context.Web.GetFileByServerRelativeUrl(url);

            context.Load(file, f => f.Exists);

            try

            {

                context.ExecuteQuery();


                if (file.Exists)

                {

                    return true;

                }

                return false;

            }

            catch (ServerUnauthorizedAccessException uae)

            {

                Log.Instance.Warn($"You are not allowed to access this file");

                throw;

            }

            catch (Exception ex)

            {

                Log.Instance.Warn($"Could not find file {url}");

                return false;

            }

        }


        //public static FieldLookupValueCollection GetLookFieldIDS(ClientContext context, string lookupValues, List lookupSourceList)

        //{

        //    SPFieldLookupValueCollection lookupIds = new SPFieldLookupValueCollection();

        //    string[] lookups = lookupValues.Split(new char[] {','},StringSplitOptions.RemoveEmptyEntries);

        //    foreach (string lookupValue in lookups)

        //    {

        //        CamlQuery query = new CamlQuery();

        //        query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>{0}</Value></Eq></Where></Query></View>", lookupValue);

        //        ListItemCollection listItems = lookupSourceList.GetItems(query);

        //        context.Load(lookupSourceList);

        //        context.Load(listItems);

        //        context.ExecuteQuery();

        //        foreach (ListItem item in listItems)

        //        {

        //            FieldLookupValue value = new FieldLookupValue(Convert.ToInt32(item["ID"]), item["Title"].ToString());

        //            lookupIds.Add(value);

        //            break;

        //        }

        //    }

        //    return lookupIds;

        //}


        public static FieldLookupValue GetLookupValue(ClientContext clientContext,string listName, string value,

   string lookupListName, string lookupFieldName, string lookupFieldType, bool onRootWeb)

        {

            List list = null;

            FieldLookupValue lookupValue = null;


            if (onRootWeb)

            {

                list = clientContext.Site.RootWeb.Lists.GetByTitle(listName);

            }

            else

            {

                list = clientContext.Web.Lists.GetByTitle(listName);

            }


            if (list != null)

            {

                CamlQuery camlQueryForItem = new CamlQuery();

                camlQueryForItem.ViewXml = string.Format(@"<View>

                  <Query>

                      <Where>

                         <Eq>

                             <FieldRef Name='{0}'/>

                             <Value Type='{1}'>{2}</Value>

                         </Eq>

                       </Where>

                   </Query>

            </View>", lookupFieldName, lookupFieldType, value);


                ListItemCollection listItems = list.GetItems(camlQueryForItem);

                clientContext.Load(listItems, items => items.Include

                                                  (listItem => listItem["ID"],

                                                   listItem => listItem[lookupFieldName]));

                clientContext.ExecuteQuery();


                if (listItems != null)

                {

                    ListItem item = listItems[0];

                    lookupValue = new FieldLookupValue();

                    lookupValue.LookupId = int.Parse(item["ID"].ToString());

                }

            }


            return lookupValue;

        }

        #endregion

    }



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



public static class ExceptionExtensions

    {

        /// <summary>

        ///     Gets the entire stack trace consisting of exception's footprints (File, Method, LineNumber)

        /// </summary>

        /// <param name="exception">Source <see cref="Exception" /></param>

        /// <returns>

        ///     <see cref="string" /> that represents the entire stack trace consisting of exception's footprints (File,

        ///     Method, LineNumber)

        /// </returns>

        public static string GetExceptionFootprints(this Exception exception)

        {

            StackTrace stackTrace = new StackTrace(exception, true);

            StackFrame[] frames = stackTrace.GetFrames();


            if (ReferenceEquals(frames, null))

            {

                return string.Empty;

            }


            var traceStringBuilder = new StringBuilder();


            for (var i = 0; i < frames.Length; i++)

            {

                StackFrame frame = frames[i];


                if (frame.GetFileLineNumber() < 1)

                    continue;


                traceStringBuilder.AppendLine($"File: {frame.GetFileName()}");

                traceStringBuilder.AppendLine($"Method: {frame.GetMethod().Name}");

                traceStringBuilder.AppendLine($"Error Message: {exception.Message}");

                traceStringBuilder.AppendLine($"LineNumber: {frame.GetFileLineNumber()}");

                //traceStringBuilder.AppendLine($"StackTrace: {exception.StackTrace}");


                if (i == frames.Length - 1)

                    break;


                traceStringBuilder.AppendLine(" ---> ");

            }


            string stackTraceFootprints = traceStringBuilder.ToString();


            if (string.IsNullOrWhiteSpace(stackTraceFootprints))

                return "NO DETECTED FOOTPRINTS";


            return stackTraceFootprints;

        }


        public static string GetExceptionEmailBody(this Exception exception, string siteURL, string htmlbody)

        {

            StackTrace stackTrace = new StackTrace(exception, true);

            StackFrame[] frames = stackTrace.GetFrames();


            if (ReferenceEquals(frames, null))

            {

                return string.Empty;

            }

            string errorhtmlBody = "";

            for (var i = 0; i < frames.Length; i++)

            {

                StackFrame frame = frames[i];


                if (frame.GetFileLineNumber() < 1)

                    continue;


                string currentFile = frame.GetFileName();

                string Method = frame.GetMethod().Name;

                string ExecptionMessage = exception.Message;

                string LineNumber = frame.GetFileLineNumber().ToString();

                string StackTrace = exception.StackTrace;

                var values = new object[] { siteURL, currentFile, Method, ExecptionMessage, LineNumber, stackTrace };

                errorhtmlBody = string.Format(htmlbody, values);

                if (i == frames.Length - 1)

                    break;                

            }            

            return errorhtmlBody;

        }

        // <summary>

        // Equivalent to Exception.ToString();

        // </summary>

        //public static string FlattenException(this Exception exception)

        //{

        //    var stringBuilder = new StringBuilder();


        //    while (exception != null)

        //    {

        //        stringBuilder.AppendLine(exception.Message);

        //        stringBuilder.AppendLine(exception.StackTrace);


        //        exception = exception.InnerException;

        //    }


        //    return stringBuilder.ToString();

        //}

    }


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




internal class KeywordsManager

    {

        /// <summary>

        /// Set Enterprise Keyword Value

        /// </summary>

        /// <param name="item">List Item</param>

        /// <param name="values">Keyword values</param>

        public static void SetTaxKeywordValue(ListItem item, string[] values)

        {

            var ctx = item.Context;

            var list = item.ParentList;

            var field = list.Fields.GetByInternalNameOrTitle(TaxKeywordFieldName);

            var taxKeywordField = ctx.CastTo<TaxonomyField>(field);

            var keywords = values.Select(value => EnsureKeyword(taxKeywordField, value)).ToList();

            taxKeywordField.SetFieldValueByValueCollection(item, new TaxonomyFieldValueCollection(ctx, GetTermsString(keywords), taxKeywordField));

            taxKeywordField.Update();

            item.Update();

            ctx.Load(item);

            ctx.ExecuteQuery();

        }



        /// <summary>

        /// Ensure Keyword 

        /// </summary>

        /// <param name="taxField"></param>

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

        /// <returns></returns>

        private static Term EnsureKeyword(TaxonomyField taxField, string name)

        {

            var ctx = taxField.Context;

            var taxSession = TaxonomySession.GetTaxonomySession(ctx);

            var termStore = taxSession.GetDefaultKeywordsTermStore();

            var keywords = termStore.KeywordsTermSet.GetAllTerms();

            var result = ctx.LoadQuery(keywords.Where(k => k.Name == name));

            ctx.ExecuteQuery();

            var keyword = result.FirstOrDefault();

            if (keyword != null)

            {

                return keyword;

            }

            keyword = termStore.KeywordsTermSet.CreateTerm(name, DefaultLanguage, Guid.NewGuid());

            ctx.Load(keyword);

            ctx.ExecuteQuery();

            return keyword;

        }


        /// <summary>

        /// Retrieve formatted Term string

        /// </summary>

        /// <param name="term"></param>

        /// <returns></returns>

        private static string GetTermString(Term term)

        {

            return string.Format("-1;#{0}{1}{2}", term.Name, TaxonomyGuidLabelDelimiter, term.Id);

        }


        private static string GetTermsString(IEnumerable<Term> terms)

        {

            var termsString = terms.Select(GetTermString).ToList();

            return string.Join(";#", termsString);

        }




        private const string TaxKeywordFieldName = "TaxKeyword";


        private const int DefaultLanguage = 1033;


        private const string TaxonomyGuidLabelDelimiter = "|";

    }





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

 /// <summary>

    /// Use this class to build your CAML xml and avoid XML issues.

    /// </summary>

    /// <example>

    /// CAML.ViewQuery(

    ///     CAML.Where(

    ///         CAML.And(

    ///             CAML.Eq(CAML.FieldValue("Project", "Integer", "{0}")),

    ///             CAML.Geq(CAML.FieldValue("StartDate","DateTime", CAML.Today()))

    ///         )

    ///     ),

    ///     CAML.OrderBy(

    ///         new OrderByField("StartDate", false),

    ///         new OrderByField("Title")

    ///     ),

    ///     rowLimit: 5

    /// );

    /// </example>

    public static class CAML

    {

        const string VIEW_XML_WRAPPER = "<View Scope=\"{0}\"><Query>{1}{2}</Query>{3}<RowLimit>{4}</RowLimit></View>";

        const string FIELD_VALUE = "<FieldRef Name='{0}' {1}/><Value Type='{2}'>{3}</Value>";

        const string FIELD_VALUE_ID = "<FieldRef ID='{0}' {1} /><Value Type='{2}'>{3}</Value>";

        const string GENERIC_CLAUSE = "<{0}>{1}</{0}>";

        const string CONDITION_CLAUSE = "<{0}>{1}{2}</{0}>";


        const string VIEW_FIELDS_CLAUSE = "<ViewFields>{0}</ViewFields>";

        const string FIELD_REF_CLAUSE = "<FieldRef Name='{0}'/>";


        const string VALUE_FOR_IN_CLAUSE = "<Value Type='{0}'>{1}</Value>";


        public static readonly string Me = "<UserId />";

        public static readonly string Month = "<Month />";

        public static readonly string Now = "<Now />";


        /// <summary>

        /// Creates the &lt;Today /&gt; node.

        /// </summary>

        /// <param name="offset">Time offset from today (+5 days or -5 days, for example).</param>

        /// <returns>Returns &lt;Today /&gt; node based on offset value</returns>

        public static string Today(int? offset = null)

        {

            if (offset.HasValue)

                return $"<Today Offset='{offset.Value}' />";

            return "<Today />";

        }


        /// <summary>

        /// Root &lt;View&gt; and &lt;Query&gt; nodes.

        /// </summary>

        /// <param name="whereClause">&lt;Where&gt; node.</param>

        /// <param name="orderByClause">&lt;OrderBy&gt; node.</param>

        /// <param name="rowLimit">&lt;RowLimit&gt; node.</param>

        /// <returns>String to be used in CAML queries</returns>

        public static string ViewQuery(string whereClause = "", string orderByClause = "", int rowLimit = 100)

        {

            return CAML.ViewQuery(ViewScope.DefaultValue, whereClause, orderByClause, string.Empty, rowLimit);

        }


        /// <summary>

        /// Root &lt;View&gt; and &lt;Query&gt; nodes.

        /// </summary>

        /// <param name="scope">View scope</param>

        /// <param name="whereClause">&lt;Where&gt; node.</param>

        /// <param name="viewFields">&lt;ViewFields&gt; node.</param>

        /// <param name="orderByClause">&lt;OrderBy&gt; node.</param>

        /// <param name="rowLimit">&lt;RowLimit&gt; node.</param>

        /// <returns>String to be used in CAML queries</returns>

        public static string ViewQuery(ViewScope scope, string whereClause = "", string orderByClause = "", string viewFields = "", int rowLimit = 100)

        {

            string viewScopeStr = scope == ViewScope.DefaultValue ? string.Empty : scope.ToString();

            return string.Format(VIEW_XML_WRAPPER, viewScopeStr, whereClause, orderByClause, viewFields, rowLimit);

        }


        /// <summary>

        /// Creates a &lt;Value&gt; node for In comparison clauses.

        /// </summary>

        /// <param name="value">Value of the field</param>

        /// <param name="fieldValueType">Value type of the field</param>

        /// <returns>Value string to be used for In comparisions in CAML queries</returns>

        public static string Value(string value, string fieldValueType)

        {

            return string.Format(VALUE_FOR_IN_CLAUSE, fieldValueType, value);

        }


        /// <summary>

        /// Creates both a &lt;FieldRef&gt; and &lt;Value&gt; nodes combination for Where clauses.

        /// </summary>

        /// <param name="fieldName">Name of the field</param>

        /// <param name="fieldValueType">Value type of the field</param>

        /// <param name="value">Value of the field</param>

        /// <param name="additionalFieldRefParams">Additional FieldRef Parameters</param>

        /// <returns>Returns FieldValue string to be used in CAML queries</returns>

        public static string FieldValue(string fieldName, string fieldValueType, string value, string additionalFieldRefParams = "")

        {

            return string.Format(FIELD_VALUE, fieldName, additionalFieldRefParams, fieldValueType, value);

        }


        /// <summary>

        /// Creates both a &lt;FieldRef&gt; and &lt;Value&gt; nodes combination for Where clauses.

        /// </summary>

        /// <param name="fieldId">Id of the field</param>

        /// <param name="fieldValueType">Value type of the field</param>

        /// <param name="value">Value of the field</param>

        /// <param name="additionalFieldRefParams">Additional FieldRef Parameters</param>

        /// <returns>Returns FieldValue string to be used in CAML queries</returns>

        public static string FieldValue(Guid fieldId, string fieldValueType, string value, string additionalFieldRefParams = "")

        {

            return string.Format(FIELD_VALUE_ID, fieldId.ToString(), additionalFieldRefParams, fieldValueType, value);

        }


        /// <summary>

        /// Creates a &lt;FieldRef&gt; node for ViewFields clause

        /// </summary>

        /// <param name="fieldName">Name of the field</param>

        /// <returns>Returns FieldRef string to be used in CAML queries</returns>

        public static string FieldRef(string fieldName)

        {

            return string.Format(FIELD_REF_CLAUSE, fieldName);

        }


        /// <summary>

        /// Creates &lt;OrederBy&gt; node for sorting by field

        /// </summary>

        /// <param name="fieldRefs">Field References</param>

        /// <returns>Returns string to be used in CAML queries</returns>

        public static string OrderBy(params OrderByField[] fieldRefs)

        {

            var sb = new StringBuilder();

            foreach (var field in fieldRefs)

            {

                sb.Append(field.ToString());

            }

            return string.Format(GENERIC_CLAUSE, CamlClauses.OrderBy, sb.ToString());

        }


        /// <summary>

        /// Creates &lt;Where&gt; node for Where clause

        /// </summary>

        /// <param name="conditionClause">The Clause condition</param>

        /// <returns>Returns string to be used in CAML queries</returns>

        public static string Where(string conditionClause)

        {

            return string.Format(GENERIC_CLAUSE, CamlClauses.Where, conditionClause);

        }


        /// <summary>

        /// Creates &lt;ViewFields&gt; node for ViewFields clause

        /// </summary>

        /// <param name="fieldRefs">Field References</param>

        /// <returns>Returns string to be used in CAML queries</returns>

        public static string ViewFields(params string[] fieldRefs)

        {

            string refs = string.Empty;


            foreach (var refField in fieldRefs)

            {

                refs += refField;

            }

            return string.Format(VIEW_FIELDS_CLAUSE, refs);

        }


        #region Conditions

        /// <summary>

        /// Creates &lt;And&gt; node 

        /// </summary>

        /// <param name="clause1">Clause</param>

        /// <param name="conditionClauses">Clause Condition</param>

        /// <returns>Returns Condition string to be used in CAML queries</returns>

        public static string And(string clause1, params string[] conditionClauses)

        {

            return Condition(CamlConditions.And, clause1, conditionClauses);

        }


        /// <summary>

        /// Creates &lt;Or&gt; node

        /// </summary>

        /// <param name="clause1">Clause</param>

        /// <param name="conditionClauses">Clause Condition</param>

        /// <returns>Returns Condition string to be used in CAML queries</returns>

        public static string Or(string clause1, params string[] conditionClauses)

        {

            return Condition(CamlConditions.Or, clause1, conditionClauses);

        }

        #endregion


        #region Comparisons

        /// <summary>

        /// Creates &lt;BeginsWith&gt; node for Comparison

        /// </summary>

        /// <param name="fieldValue">Value of the field</param>

        /// <returns>Returns Comparison string to be used in CAML queries</returns>

        public static string BeginsWith(string fieldValue)

        {

            return Comparison(CamlComparisions.BeginsWith, fieldValue);

        }

        /// <summary>

        /// Creates &lt;Contains&gt; node for Comparison

        /// </summary>

        /// <param name="fieldValue">Value of the field</param>

        /// <returns>Returns Comparison string to be used in CAML queries</returns>

        public static string Contains(string fieldValue)

        {

            return Comparison(CamlComparisions.Contains, fieldValue);

        }

        /// <summary>

        /// Creates &lt;DateRangesOverlap&gt; node for Comparison

        /// </summary>

        /// <param name="fieldValue">Value of the field</param>

        /// <returns>Returns Comparison string to be used in CAML queries</returns>

        public static string DateRangesOverlap(string fieldValue)

        {

            return Comparison(CamlComparisions.DateRangesOverlap, fieldValue);

        }

        /// <summary>

        /// Creates &lt;Eq&gt; node for Comparison

        /// </summary>

        /// <param name="fieldValue">Value of the field</param>

        /// <returns>Returns Comparison string to be used in CAML queries</returns>

        public static string Eq(string fieldValue)

        {

            return Comparison(CamlComparisions.Eq, fieldValue);

        }

        /// <summary>

        /// Creates &lt;Geq&gt; node for Comparison

        /// </summary>

        /// <param name="fieldValue">Value of the field</param>

        /// <returns>Returns Comparison string to be used in CAML queries</returns>

        public static string Geq(string fieldValue)

        {

            return Comparison(CamlComparisions.Geq, fieldValue);

        }

        /// <summary>

        /// Creates &lt;Gt&gt; node for Comparison

        /// </summary>

        /// <param name="fieldValue">Value of the field</param>

        /// <returns>Returns Comparison string to be used in CAML queries</returns>

        public static string Gt(string fieldValue)

        {

            return Comparison(CamlComparisions.Gt, fieldValue);

        }

        /// <summary>

        /// Creates &lt;In&gt; node for Comparison

        /// </summary>

        /// <param name="fieldValue">Value of the field</param>

        /// <returns>Returns Comparison string to be used in CAML queries</returns>

        public static string In(string fieldValue)

        {

            return Comparison(CamlComparisions.In, fieldValue);

        }

        /// <summary>

        /// Creates &lt;In&gt; node for Comparison

        /// </summary>

        /// <param name="fieldRef">Field Reference</param>

        /// <param name="values">Value strings to be included inside the &lt;In&gt;-clause</param>

        /// <returns>Returns Comparison string to be used in CAML queries</returns>

        public static string In(string fieldRef, params string[] values)

        {

            var fieldValue = fieldRef;

            fieldValue += "<Values>";

            foreach (var value in values)

            {

                fieldValue += value;

            }

            fieldValue += "</Values>";

            return In(fieldValue);

        }

        /// <summary>

        /// Creates &lt;Includes&gt; node for Comparison

        /// </summary>

        /// <param name="fieldValue">Value of the field</param>

        /// <returns>Returns Comparison string to be used in CAML queries</returns>

        public static string Includes(string fieldValue)

        {

            return Comparison(CamlComparisions.Includes, fieldValue);

        }

        /// <summary>

        /// Creates &lt;IsNotNull&gt; node for Comparison

        /// </summary>

        /// <param name="fieldValue">Value of the field</param>

        /// <returns>Returns Comparison string to be used in CAML queries</returns>

        public static string IsNotNull(string fieldValue)

        {

            return Comparison(CamlComparisions.IsNotNull, fieldValue);

        }

        /// <summary>

        /// Creates &lt;IsNull&gt; node for Comparison

        /// </summary>

        /// <param name="fieldValue">Value of the field</param>

        /// <returns>Returns Comparison string to be used in CAML queries</returns>

        public static string IsNull(string fieldValue)

        {

            return Comparison(CamlComparisions.IsNull, fieldValue);

        }

        /// <summary>

        /// Creates &lt;Leq&gt; node for Comparison

        /// </summary>

        /// <param name="fieldValue">Value of the field</param>

        /// <returns>Returns Comparison string to be used in CAML queries</returns>

        public static string Leq(string fieldValue)

        {

            return Comparison(CamlComparisions.Leq, fieldValue);

        }

        /// <summary>

        /// Creates &lt;Lt&gt; node for Comparison

        /// </summary>

        /// <param name="fieldValue">Value of the field</param>

        /// <returns>Returns Comparison string to be used in CAML queries</returns>

        public static string Lt(string fieldValue)

        {

            return Comparison(CamlComparisions.Lt, fieldValue);

        }

        /// <summary>

        /// Creates &lt;Neq&gt; node for Comparison

        /// </summary>

        /// <param name="fieldValue">Value of the field</param>

        /// <returns>Returns Comparison string to be used in CAML queries</returns>

        public static string Neq(string fieldValue)

        {

            return Comparison(CamlComparisions.Neq, fieldValue);

        }

        /// <summary>

        /// Creates &lt;NotIncludes&gt; node for Comparison

        /// </summary>

        /// <param name="fieldValue">Value of the field</param>

        /// <returns>Returns Comparison string to be used in CAML queries</returns>

        public static string NotIncludes(string fieldValue)

        {

            return Comparison(CamlComparisions.NotIncludes, fieldValue);

        }

        #endregion


        static string Comparison(CamlComparisions comparison, string fieldValue)

        {

            return string.Format(GENERIC_CLAUSE, comparison, fieldValue);

        }


        static string Condition(CamlConditions condition, string clause1, params string[] comparisonClauses)

        {

            var formattedString = clause1;


            foreach (var clause in comparisonClauses)

            {

                formattedString = string.Format(CONDITION_CLAUSE, condition, formattedString, clause);

            }


            return formattedString;

        }


        enum CamlComparisions

        {

            BeginsWith, Contains, DateRangesOverlap,

            Eq, Geq, Gt, In, Includes, IsNotNull, IsNull,

            Leq, Lt, Neq, NotIncludes

        }

        enum CamlConditions { And, Or }

        enum CamlClauses { Where, OrderBy, GroupBy }


    }


    /// <summary>

    /// Class is used to order the data by field.

    /// </summary>

    public class OrderByField

    {

        const string ORDERBY_FIELD = "<FieldRef Name='{0}' Ascending='{1}' />";

        /// <summary>

        /// Constructor for OrderByField class

        /// </summary>

        /// <param name="name">Name of the field</param>

        public OrderByField(string name) : this(name, true) { }

        /// <summary>

        /// Constructor for OrderByField class

        /// </summary>

        /// <param name="name">Name of the field</param>

        /// <param name="ascending">If we want to order in ascending order</param>

        public OrderByField(string name, bool ascending)

        {

            Name = name;

            Ascending = ascending;

        }

        /// <summary>

        /// Gets or sets the name of the field

        /// </summary>

        public string Name { get; set; }

        /// <summary>

        /// Gets or sets the Ascending order flag

        /// </summary>

        public bool Ascending { get; set; }

        /// <summary>

        /// OrderByField string

        /// </summary>

        /// <returns>Returns string</returns>

        public override string ToString()

        {

            return string.Format(ORDERBY_FIELD, Name, Ascending.ToString().ToUpper());

        }

    }


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


 public class PnPAuthenticationManager

    {

        private bool isAuthenticated;

        /// <summary>

        /// Enum to identify the supported Office 365 hosting environments

        /// </summary>

        public enum SPOEnvironment

        {

            Production = 0,

            UAT = 1,

            SIT = 2,

            DEV = 3,

            INT = 4

        }


        public enum EnviromentValue

        {

            o365=0,

            onpremises=1,

            extranet=2

        } 

              

        #region Construction

        public PnPAuthenticationManager()

        {

            isAuthenticated = false;

        }

        #endregion

        /// <summary>

        /// Return ClientContext of online or onpremise

        /// </summary>

        /// <param name="TargetSiteUrl"></param>

        /// <param name="ev">o365=0,onpremises=1,extranet=2</param>

        /// <returns></returns>

        public ClientContext pnp_AuthenticateUser(Uri TargetSiteUrl, EnviromentValue ev)

        {

            ClientContext context = null;

            try

            {

                // Based on the environmentvalue provided it execute the function.

                if (string.Compare(ev.ToString(), "onpremises", StringComparison.OrdinalIgnoreCase) == 0)

                {

                    context = pnp_GetWebLoginClientContext(TargetSiteUrl.AbsoluteUri, ev);

                    // isAuthenticated = true;

                    // You can write additional methods here which you want to use after authentication

                }

                else if (string.Compare(ev.ToString(), "o365", StringComparison.OrdinalIgnoreCase) == 0)

                {

                    context = pnp_GetWebLoginClientContext(TargetSiteUrl.AbsoluteUri, ev);

                    // isAuthenticated = true;

                    // You can write additional methods here which you want to use after authentication

                }

            }

            catch (Exception ex)

            {

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

                Log.Instance.Error(exString);

                MailUtility.SendEmailNotification(context, NotificationKindType.Error.ToString(), ex);

            }

            return context;

        }


        /// <summary>

        /// Return ClientContext of SharePoint Online/Onpremsie using username nand password.

        /// </summary>

        /// <param name="TargetSiteUrl"></param>

        /// <param name="Environmentvalue"></param>

        /// <param name="username"></param>

        /// <param name="password"></param>

        /// <returns></returns>

        public ClientContext pnp_AuthenticateUserbycredential(Uri siteUrl, string username, string password, ref bool isAuthenticated)

        {

            ClientContext context = null;

            try

            {

                context = pnp_GetSharePointOnlineAuthenticatedContextTenant(siteUrl.AbsoluteUri, username, password);

                isAuthenticated = true;              

            }

            catch (Exception ex)

            {

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

                Log.Instance.Error(exString);

                MailUtility.SendEmailNotification(context, NotificationKindType.Error.ToString(), ex);

            }

            return context;

        }


        /// <summary>

        /// Return app based clientcontext of sharepoint online

        /// </summary>

        /// <param name="TargetSiteUrl"></param>

        /// <param name="appId"></param>

        /// <param name="appSecret"></param>

        /// <param name="isAuthenticated"></param>

        /// <returns></returns>

        public ClientContext pnp_AuthenticateApponly(Uri TargetSiteUrl, string appId, string appSecret,ref bool isAuthenticated)

        {

            ClientContext context = null;            

            try

            {

                // Based on the environmentvalue provided it execute the function.

                context = pnp_GetAppOnlyAuthenticatedContext(TargetSiteUrl.AbsoluteUri, appId, appSecret);

                isAuthenticated = true;

            }

            catch (Exception ex)

            {

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

                Log.Instance.Error(exString);

                MailUtility.SendEmailNotification(context, NotificationKindType.Error.ToString(), ex);

            }

            return context;

        }


        #region Authenticating against SharePoint Online using credentials or app-only


        /// <summary>

        /// Returns a SharePointOnline ClientContext object

        /// </summary>

        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>

        /// <param name="tenantUser">User to be used to instantiate the ClientContext object</param>

        /// <param name="tenantUserPassword">Password of the user used to instantiate the ClientContext object</param>

        /// <returns>ClientContext to be used by CSOM code</returns>

        private ClientContext pnp_GetSharePointOnlineAuthenticatedContextTenant(string siteUrl, string tenantUser, string tenantUserPassword)

        {

            var spoPassword = EncryptionUtility.ToSecureString(tenantUserPassword);

            return pnp_GetSharePointOnlineAuthenticatedContextTenant(siteUrl, tenantUser, spoPassword);

        }


        /// <summary>

        /// Returns a SharePointOnline ClientContext object

        /// </summary>

        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>

        /// <param name="tenantUser">User to be used to instantiate the ClientContext object</param>

        /// <param name="tenantUserPassword">Password (SecureString) of the user used to instantiate the ClientContext object</param>

        /// <returns>ClientContext to be used by CSOM code</returns>

        private ClientContext pnp_GetSharePointOnlineAuthenticatedContextTenant(string siteUrl, string tenantUser, SecureString tenantUserPassword)

        {

            Log.Instance.Info(Log.LOGGING_SOURCE, "AuthenticationManager_GetContext", siteUrl);

            Log.Instance.Debug(Log.LOGGING_SOURCE, "AuthenticationManager_TenantUser", tenantUser);

            ClientContext ctx = null;

            AuthenticationManager authManager = new AuthenticationManager(tenantUser, tenantUserPassword);

            //string accessToken = authManager.GetAccessToken(siteUrl);

            ctx = authManager.GetContext(siteUrl);

            try

            {

                ctx.Load(ctx.Web);

                ctx.ExecuteQuery();

                Log.Instance.Info("You have connected to {0} site..", ctx.Web.Title);

            }

            catch (Exception ex)

            {

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

                Log.Instance.Error(exString);

            }

            return ctx;

        }



        /// <summary>

        /// Returns an app only ClientContext object

        /// </summary>

        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>

        /// <param name="appId">Application ID which is requesting the ClientContext object</param>

        /// <param name="appSecret">Application secret of the Application which is requesting the ClientContext object</param>

        /// <returns>ClientContext to be used by CSOM code</returns>

        private ClientContext pnp_GetAppOnlyAuthenticatedContext(string siteUrl, string appId, string appSecret)

        {

            ClientContext ctx = null;

            AuthenticationManager am = new AuthenticationManager();

            ctx = am.GetACSAppOnlyContext(siteUrl, appId, appSecret);

            try

            {

                Web web = ctx.Web;

                ctx.Load(web);

                ctx.ExecuteQuery();

                Log.Instance.Info("You have connected to {0} site..", web.Title);

            }

            catch (Exception ex)

            {

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

                Log.Instance.Error(exString);

            }

            return ctx;

        }


        /// <summary>

        /// Returns an app only ClientContext object

        /// </summary>

        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>

        /// <param name="appId">Application ID which is requesting the ClientContext object</param>

        /// <param name="appSecret">Application secret of the Application which is requesting the ClientContext object</param>

        /// <param name="environment">SharePoint environment being used</param>

        /// <returns>ClientContext to be used by CSOM code</returns>

        private ClientContext pnp_GetAppOnlyAuthenticatedContext(string siteUrl, string appId, string appSecret, SPOEnvironment environment)

        {

            ClientContext ctx = null;

            if (SPOEnvironment.Production == environment)

            {

                Log.Instance.Info(Log.LOGGING_SOURCE, environment.ToString(),string.Format("ClientID: {0} \n ClientSecret:{1}",appId,appSecret)); 

                ctx = pnp_GetAppOnlyAuthenticatedContext(siteUrl, appId, appSecret);

                Log.Instance.Debug(Log.LOGGING_SOURCE, environment.ToString(), string.Format("ClientID: {0} \n ClientSecret:{1}", appId, appSecret));

            }

            else if (SPOEnvironment.UAT == environment)

            {

                Log.Instance.Info(Log.LOGGING_SOURCE, environment.ToString(), string.Format("ClientID: {0} \n ClientSecret:{1}", appId, appSecret));

                ctx = pnp_GetAppOnlyAuthenticatedContext(siteUrl, appId, appSecret);

                Log.Instance.Debug(Log.LOGGING_SOURCE, environment.ToString(), string.Format("ClientID: {0} \n ClientSecret:{1}", appId, appSecret));

            }

            else if (SPOEnvironment.SIT == environment)

            {

                Log.Instance.Info(Log.LOGGING_SOURCE, environment.ToString(), string.Format("ClientID: {0} \n ClientSecret:{1}", appId, appSecret));

                ctx = pnp_GetAppOnlyAuthenticatedContext(siteUrl, appId, appSecret);

                Log.Instance.Debug(Log.LOGGING_SOURCE, environment.ToString(), string.Format("ClientID: {0} \n ClientSecret:{1}", appId, appSecret));

            }

            else if (SPOEnvironment.DEV == environment)

            {

                Log.Instance.Info(Log.LOGGING_SOURCE, environment.ToString(), string.Format("ClientID: {0} \n ClientSecret:{1}", appId, appSecret));

                ctx = pnp_GetAppOnlyAuthenticatedContext(siteUrl, appId, appSecret);

                Log.Instance.Debug(Log.LOGGING_SOURCE, environment.ToString(), string.Format("ClientID: {0} \n ClientSecret:{1}", appId, appSecret));

            }

            return ctx;

        }

       

        /// <summary>

        /// Returns a SharePoint on-premises / SharePoint Online ClientContext object. Requires claims based authentication with FedAuth cookie.

        /// </summary>

        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>

        /// <param name="icon">Optional icon to use for the popup form</param>

        /// <param name="scriptErrorsSuppressed">Optional parameter to set WebBrowser.ScriptErrorsSuppressed value in the popup form</param>

        /// <param name="loginRequestUri">Optional URL to use to log the user in to a specific page. If not provided, the <paramref name="siteUrl"/> will be used.</param>

        /// <returns>ClientContext to be used by CSOM code</returns>

        private ClientContext pnp_GetWebLoginClientContext(string siteUrl,EnviromentValue ev)

        {

            ClientContext context = null;

            var siteUri = new Uri(siteUrl);

            var networkCredential=CredentialManager.GetCredential(Appsetting.SPOAccess);

            var authManager = new AuthenticationManager(networkCredential.UserName,networkCredential.SecurePassword);            

            if (authManager != null && ev==EnviromentValue.o365)

            {

                //context.Credentials = CredentialManager.GetSharePointOnlineCredential(Appsetting.SPOAccess);

                // This method calls a pop up window with the login page and it also prompts 

                // for the multi factor authentication code. 


                context = Task.Run(() => authManager.GetContextAsync(siteUrl)).GetAwaiter().GetResult();

                // The obtained ClientContext object can be used to connect to the SharePoint site.

            }

            else if(context != null && ev == EnviromentValue.onpremises)

            {

                context.Credentials = CredentialManager.GetCredential(Appsetting.SPOAccess);

            }

            try

            {

                Web web = context.Web;

                context.Load(web, w => w.Title);

                context.ExecuteQuery();

                Log.Instance.Info("You have connected to {0} site..", web.Title);

            }

            catch (Exception ex)

            {

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

                Log.Instance.Error(exString);

            }

            return context;

        }

       

        /// <summary>

        /// Get the access token lease time span.

        /// </summary>

        /// <param name="expiresOn">The ExpiresOn time of the current access token</param>

        /// <returns>Returns a TimeSpan represents the time interval within which the current access token is valid thru.</returns>

        private TimeSpan GetAccessTokenLease(DateTime expiresOn)

        {

            DateTime now = DateTime.UtcNow;

            DateTime expires = expiresOn.Kind == DateTimeKind.Utc ?

                expiresOn : TimeZoneInfo.ConvertTimeToUtc(expiresOn);

            TimeSpan lease = expires - now;

            return lease;

        }


        #endregion


        #region Authenticating against SharePoint on-premises using credentials

        /// <summary>

        /// Returns a SharePoint on-premises / SharePoint Online Dedicated ClientContext object

        /// </summary>

        /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>

        /// <param name="user">User to be used to instantiate the ClientContext object</param>

        /// <param name="password">Password of the user used to instantiate the ClientContext object</param>

        /// <param name="domain">Domain of the user used to instantiate the ClientContext object</param>

        /// <returns>ClientContext to be used by CSOM code</returns>

        private ClientContext pnp_GetNetworkCredentialAuthenticatedContext(string siteUrl, string user, string password, string domain)

        {

            ClientContext clientContext = new ClientContext(siteUrl)

            {


                DisableReturnValueCache = true,


                Credentials = new System.Net.NetworkCredential(user, password, domain)

            };

            return clientContext;

        }

        #endregion


        #region SharePoint online/onpremise classic authentication using csom 

        /// <summary>

        /// Main method to call

        /// Provide the environment in which the site resides. One of the below options.

        ///(i) onpremises (ii) o365 (iii) extranet

        /// </summary>

        /// <param name="TargetSiteUrl"></param>

        /// <param name="Environmentvalue"></param>

        /// <param name="username"></param>

        /// <param name="password"></param>

        private static void AuthenticateUser(Uri TargetSiteUrl, string Environmentvalue, string username, string password)

        {

            try

            {

                // Based on the environmentvalue provided it execute the function.

                if (string.Compare(Environmentvalue, "onpremises", StringComparison.OrdinalIgnoreCase) == 0)

                {

                    ClientContext Context = LogOn(username, password, TargetSiteUrl);

                    // isAuthenticated = true;

                    // You can write additional methods here which you want to use after authentication

                }

                else if (string.Compare(Environmentvalue, "o365", StringComparison.OrdinalIgnoreCase) == 0)

                {

                    ClientContext Context = O365LogOn(username, password, TargetSiteUrl);

                    // isAuthenticated = true;

                    // You can write additional methods here which you want to use after authentication

                }

                else if (string.Compare(Environmentvalue, "extranet", StringComparison.OrdinalIgnoreCase) == 0)

                {

                    ClientContext Context = ExtranetLogOn(username, password, TargetSiteUrl);

                    // isAuthenticated = true;

                    // You can write additional methods here which you want to use after authentication

                }

            }

            catch (Exception ex)

            {

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

                Log.Instance.Error(exString);

            }

        }

        /// <summary>

        /// Authenticate SharePoint onpremise site using csom

        /// </summary>

        /// <param name="userName"></param>

        /// <param name="password"></param>

        /// <param name="url"></param>

        /// <returns></returns>

        private static ClientContext LogOn(string userName, string password, Uri url)

        {

            ClientContext clientContext = null;

            ClientContext ctx = null;

            try

            {

                clientContext = new ClientContext(url);


                // Condition to check whether the user name is null or empty.

                if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))

                {

                    SecureString securestring = new SecureString();

                    password.ToCharArray().ToList().ForEach(s => securestring.AppendChar(s));

                    clientContext.Credentials = new System.Net.NetworkCredential(userName, securestring);

                    clientContext.ExecuteQuery();

                }

                else

                {

                    clientContext.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

                    clientContext.ExecuteQuery();

                }


                ctx = clientContext;

            }

            catch (Exception ex)

            {

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

                Log.Instance.Error(exString);

            }

            finally

            {

                if (clientContext != null)

                {

                    clientContext.Dispose();

                }

            }

            return ctx;

        }

        /// <summary>

        /// Authenticate SharePoint online site using csom

        /// </summary>

        /// <param name="userName"></param>

        /// <param name="password"></param>

        /// <param name="url"></param>

        /// <returns></returns>

        private static ClientContext O365LogOn(string userName, string password, Uri url)

        {

            ClientContext clientContext = null;

            ClientContext ctx = null;

            try

            {

                clientContext = new ClientContext(url);


                // Condition to check whether the user name is null or empty.

                if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))

                {

                    SecureString securestring = new SecureString();

                    password.ToCharArray().ToList().ForEach(s => securestring.AppendChar(s));

                    clientContext.Credentials = new SharePointOnlineCredentials(userName, securestring);

                    clientContext.ExecuteQuery();

                }

                else

                {

                    clientContext.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

                    clientContext.ExecuteQuery();

                }

                ctx = clientContext;

            }

            catch (Exception ex)

            {

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

                Log.Instance.Error(exString);

            }

            finally

            {

                if (clientContext != null)

                {

                    clientContext.Dispose();

                }

            }

            return ctx;

        }    


        /// <summary>

        /// Authenticate extranet site 

        /// </summary>

        /// <param name="userName"></param>

        /// <param name="password"></param>

        /// <param name="url"></param>

        /// <returns></returns>

        private static ClientContext ExtranetLogOn(string userName, string password, Uri url)

        {

            ClientContext clientContext = null;

            ClientContext ctx;

            try

            {

                clientContext = new ClientContext(url);


                // Condition to check whether the user name is null or empty.

                if (!string.IsNullOrEmpty(userName))

                {

                    System.Net.NetworkCredential networkCredential = new System.Net.NetworkCredential(userName, password);

                    System.Net.CredentialCache cc = new System.Net.CredentialCache();

                    cc.Add(url, "NTLM", networkCredential);

                    clientContext.Credentials = cc;

                    clientContext.ExecuteQuery();

                }

                else

                {

                    System.Net.CredentialCache cc = new System.Net.CredentialCache();

                    cc.Add(url, "NTLM", System.Net.CredentialCache.DefaultNetworkCredentials);

                    clientContext.Credentials = cc;

                    clientContext.ExecuteQuery();

                }

                ctx = clientContext;

            }

            finally

            {

                if (clientContext != null)

                {

                    clientContext.Dispose();

                }

            }

            return ctx;

        }


        #endregion

    }





static async Task Main(string[] args)

        {                       

            //var dt = ExcelManager.ConvertCSVTexttoDataTable(Properties.Resources.ES_Migration_Master);

            bool isAuthenticated = false;


            #region for Production context line of code

            //string SourceSiteURL = Appsetting.Source_Prod_SiteURL;

            //string TargetSiteURL = Appsetting.Target_Prod_SiteURL;


            //ClientContext context = Appsetting.pnpauthManager.pnp_AuthenticateApponly(new Uri(SourceSiteURL), Appsetting.ClientId_Prod_Source, Appsetting.ClientSecret_Prod_Source, ref isAuthenticated);

            //ClientContext tcontext = Appsetting.pnpauthManager.pnp_AuthenticateApponly(new Uri(TargetSiteURL), Appsetting.ClientId_Prod_Traget, Appsetting.ClientSecret_Prod_Target, ref isAuthenticated);

            #endregion


            //ClientContext context = Appsetting.pnpauthManager.pnp_AuthenticateApponly(new Uri(Appsetting.siteURL_Dev), Appsetting.ClientId_DEV, Appsetting.ClientSecret_DEV, ref isAuthenticated);

            ClientContext context = Appsetting.pnpauthManager.pnp_AuthenticateApponly(new Uri(Appsetting.siteURL_INT), Appsetting.ClientId_INT, Appsetting.ClientSecret_INT, ref isAuthenticated);

            ClientContext tcontext = Appsetting.pnpauthManager.pnp_AuthenticateApponly(new Uri(Appsetting.siteURL_UAT), Appsetting.ClientId_UAT, Appsetting.ClientSecret_UAT, ref isAuthenticated);


            Stopwatch sw = new Stopwatch();

            sw.Start();

            try

            {

                #region Copy all folder structure and files to other sharepoint online library

                //FolderExtensions.CopyAllFilesToCrossSite(SourceSiteURL, TargetSiteURL, sourceLibName, targetLibName); 

                //FolderExtensions.CopyAllFilesToCrossSite(Appsetting.siteURL_Dev, Appsetting.siteURL_INT, "Submissions", "Submissions", "New Account");

                #endregion


                #region Copy all documentset type folder with their files to other sharepoint online library                

                //await DocumentSetExtension.CopyAllDocumentSetWithMetaData(tcontext, context, sourceLibName, targetLibName, "New Account");

                #endregion


                #region as below method used for export file or document set information into excel                                 

                //FolderExtensions.GetAllFiles(context, Appsetting.Source_Prod_ListName);

                //FolderExtensions.GetAllFiles(tcontext, "Submissions-Healthcare");

                //FolderExtensions.GetDocumentSetsInfo(tcontext, Appsetting.Target_Prod_ListName, "New Account");

                #endregion


                #region All E&S Migration activity method call as below

                //BusinessRule businessRule = new BusinessRule(context, tcontext, LOB.Healthcare);

                BusinessRule businessRule = new BusinessRule(context, tcontext, LOB.FinancialLines);

                var sourceFolderStructures = await businessRule.getAllFileStructurefromSourceLibraryExcel();

                //await SPFileMigrationExtension.CopyAllFiletoDocumentSetWithMetaData(context, tcontext, sourceFolderStructures, Appsetting.Source_Prod_ListName, Appsetting.Target_Prod_ListName, "New Account");

                #endregion


            }

            catch (Exception ex)

            {

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

                Log.Instance.Error(exString);

                //MailUtility.SendEmailNotification(context, "Error", ex);

            }            

            sw.Stop();

            string swET = string.Format("Total Elapsied time (HH:mm:ss) -- {0}:{1}:{2}", sw.Elapsed.Hours.ToString(), sw.Elapsed.Minutes.ToString(), sw.Elapsed.Seconds.ToString());

            Console.WriteLine(swET);                           

            Console.ReadLine();

        }