Imports System.IO
Imports Microsoft.SharePoint

Public Class Common
    Private Shared configValues As String()
    Private Shared fullFilepath As String
    Public Shared fsPath As String = "C:\Temp\"


    Private Shared Sub CreateFolder()
        Dim fileName As String
        Dim relativeUrlToFolder As String
        Dim filePaths As String() = Directory.GetFiles(configValues(3) + configValues(2) + "\", "*.*", SearchOption.AllDirectories)
        Dim sp As New SPSite(configValues(0))
        Dim site As SPWeb = sp.OpenWeb(configValues(4))
        site.AllowUnsafeUpdates = True
        Dim folder As SPFolder = site.GetFolder(configValues(1))
        Dim files As SPFileCollection = folder.Files
        Dim list As SPList = site.Lists(configValues(1))
        For Each fullPath As String In filePaths
            fileName = Path.GetFileName(fullPath)
            Dim fStream As FileStream = File.OpenRead(fullPath)
            Dim contents As Byte() = New Byte(fStream.Length) {}
            fStream.Read(contents, 0, CInt(fStream.Length))
            fStream.Close()
            relativeUrlToFolder = RelativeUrlToFolder1(fullPath, fileName)
            Dim sNames As String() = SubfolderNames1(relativeUrlToFolder)
            Dim i As Integer = 0
            For Each subName As String In sNames
                If i = sNames.Length - 1 Then
                    Exit For
                End If
                Dim validateFolderExists As SPFolder = site.GetFolder(configValues(0) + configValues(4) + "/" + configValues(1) + subName)
                If Not validateFolderExists.Exists Then
                    folder.SubFolders.Add(configValues(0) + configValues(4) + "/" + configValues(1) + subName)
                    i += 1
                End If
            Next
        Next
    End Sub
    Private Shared Function RelativeUrlToFolder1(ByVal fullPath As String, ByVal fileName As String) As String
        Dim storeFolder As String
        storeFolder = configValues(2)
        Dim folderStoreLength As Integer
        folderStoreLength = storeFolder.Length
        Dim fullPathLength As Integer
        fullPathLength = fullPath.Length
        Dim fileNameLength As Integer
        fileNameLength = fileName.Length
        fullPath = fullPath.Remove(0, folderStoreLength + 3)
        fullPathLength = fullPath.Length
        fullPath = fullPath.Remove(fullPathLength - fileNameLength, fileNameLength)
        fullPath = fullPath.Replace("\", "/")
        Return fullPath
    End Function
    Private Shared Function SubfolderNames1(ByVal fullPath As String) As String()
        Dim delimiterChars As Char() = {"/"c}
        Dim subfolderNames As String() = fullPath.Split(delimiterChars)
        Dim concatSubNames As String = ""
        Dim subfolderNamesUrl As String()
        subfolderNamesUrl = New String(subfolderNames.Length) {}
        Dim i As Integer = 0
        For Each sNames As String In subfolderNames
            concatSubNames = concatSubNames + sNames + "/"
            subfolderNamesUrl(i) = concatSubNames.Remove(concatSubNames.Length - 1, 1)
            i += 1
        Next
        Return subfolderNamesUrl
    End Function
    Public Shared Sub UploadFiles(ByVal dicParameters As Dictionary(Of String, String), Optional ByVal dicColumns As Dictionary(Of String, String) = Nothing)

        If dicColumns Is Nothing Then
            dicColumns = New Dictionary(Of String, String)
        End If

        'If Form1.treeSP.SelectedNode Is Nothing Then
        '    MessageBox.Show("Please select sharepoint location")
        '    Exit Sub
        'End If

       
        Dim SPURL As String = dicParameters.Item("URL")
        Dim arraSPurl() As String = SPURL.Split("/")

        configValues = New String(4) {}
        configValues(0) = arraSPurl(0) + "//" + arraSPurl(2)
        configValues(1) = dicParameters.Item("CurrentNodePath")
        configValues(2) = "temp"
        configValues(3) = "c:\"
        configValues(4) = dicParameters.Item("ParentNodePath")

        Dim fileName As String
        Dim relativeUrlToFolder As String
        Dim filePaths As String() = Directory.GetFiles(fsPath, "*.*", SearchOption.AllDirectories)
        Dim sp As New SPSite(configValues(0))
        Dim site As SPWeb = sp.OpenWeb(configValues(4))
        site.AllowUnsafeUpdates = True

        Dim folder As SPFolder = site.GetFolder(configValues(1))
        Dim files As SPFileCollection = folder.Files
        Dim list As SPList = site.Lists(configValues(1))
        CreateFolder()

        For Each fullPath As String In filePaths
            fileName = Path.GetFileName(fullPath)
            Dim fStream As FileStream = File.OpenRead(fullPath)
            Dim contents As Byte() = New Byte(fStream.Length - 1) {}
            fStream.Read(contents, 0, CInt(fStream.Length))
            fStream.Close()
            relativeUrlToFolder = RelativeUrlToFolder1(fullPath, fileName)
            Dim sNames As String() = SubfolderNames1(relativeUrlToFolder)

            'Removing disallowed characters from file name
            fileName = fileName.Replace("\", "")
            fileName = fileName.Replace("/", "")
            fileName = fileName.Replace(":", "")
            fileName = fileName.Replace("*", "")
            fileName = fileName.Replace("?", "")
            fileName = fileName.Replace("<", "")
            fileName = fileName.Replace(">", "")
            fileName = fileName.Replace("|", "")
            fileName = fileName.Replace("#", "")
            fileName = fileName.Replace("{", "")
            fileName = fileName.Replace("}", "")
            fileName = fileName.Replace("%", "")
            fileName = fileName.Replace("~", "")
            fileName = fileName.Replace("&", "")


            If fileName.Length > 128 Then
                fileName = Path.GetFileNameWithoutExtension(fullPath)
                Dim fileextension As String = Path.GetExtension(fullPath)
                fileName = fileName.Substring(0, (128 - fileextension.Length))
                fileName = fileName + fileextension
            End If

            For Each subName As String In sNames
                If relativeUrlToFolder = "/" Then
                    fullFilepath = ((((configValues(0)) + configValues(4) & "/") + configValues(1) & "/") + fileName)

                    Dim currentFile As SPFile = files.Add(fullFilepath, contents, True)

                    If (dicColumns.Count <> 0) Then
                        ApplyMetaData(dicColumns, currentFile.Item)
                    End If
                    currentFile.CheckIn("Upload")
                    Exit For
                Else
                    fullFilepath = ((((configValues(0)) + configValues(4) & "/") + configValues(1)) + relativeUrlToFolder + fileName)

                    If site.GetFile(fullFilepath).Exists Then
                        site.GetFile(fullFilepath).CheckOut()
                    End If
                    Dim currentFile As SPFile = files.Add(fullFilepath, contents, True)

                    If (dicColumns.Count <> 0) Then
                        ApplyMetaData(dicColumns, currentFile.Item)
                    End If
                    currentFile.CheckIn("Upload")
                    Exit For
                End If
            Next
        Next

    End Sub
    Public Shared Sub DeleteFolder(ByVal FolderPath As String)
        If System.IO.Directory.Exists(FolderPath) Then
            System.IO.Directory.Delete(FolderPath, True)
        End If
    End Sub

    Private Shared Sub ApplyMetaData(ByVal dicColumns As Dictionary(Of String, String), ByRef listitem As SPListItem)
        For Each kvp As KeyValuePair(Of String, String) In dicColumns
            ' Find a Particular Control by its Type
            listitem(kvp.Key) = kvp.Value
        Next
        Try
            listitem.Update()
        Catch ex As Exception

        End Try
    End Sub
End Class
