#Region "Imports"
Imports System
Imports System.Windows.Forms
Imports System.Threading
Imports MSXML
Imports Microsoft.Office.Interop.Outlook
Imports OutLookApp = Microsoft.Office.Interop.Outlook.Application
Imports Microsoft.SharePoint
Imports Microsoft.SharePoint.Administration
Imports System.IO
#End Region
Public Class Migration
#Region "Variable Declaration"
    Public strFolderName As String
    Dim alCheckedExFolders As New ArrayList
    Dim alCheckedExMailFolders As New ArrayList
    Dim filepathlen As Integer
    Dim fullFilepath As String
    Private fiCount As Integer
    Private fsPath As String = "C:\Temp\"
    Dim configValues As String()
    Private WithEvents BackWorker As System.ComponentModel.BackgroundWorker
#End Region
#Region "Events"
    Private Sub treeExPublicFolder_AfterCheck(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles treeExPublicFolder.AfterCheck
        Dim sURI As String = e.Node.FullPath.Replace("Personal Folders", "")
        sURI = sURI.Replace("\", "/")

        If e.Node.Checked = True Then
            alCheckedExMailFolders.Add(sURI)
        ElseIf e.Node.Checked = False Then
            alCheckedExMailFolders.Remove(sURI)
        End If
    End Sub
    Private Sub treeExPublicFolder_AfterCollapse(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles treeExPublicFolder.AfterCollapse
    End Sub
    Private Sub treeExPublicFolder_AfterExpand(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles treeExPublicFolder.AfterExpand
    End Sub
    Private Sub btnSPBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSPBrowse.Click
        Dim oSite As SPSite = New SPSite(txtSPURL.Text)
        Dim oSPWebRoot As SPWeb = oSite.OpenWeb
        treeSP.ImageIndex = 0
        treeSP.SelectedImageIndex = 0
        treeSP.Nodes.Add(oSPWebRoot.Title)
        FillSubWeb(treeSP.Nodes(0), oSite.OpenWeb)
        btnSP.Visible = True
        btnAddMetaData.Visible = True
    End Sub
    Private Sub btnSP_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSP.Click
        SaveDocumentInTempFolder()
        If Not Directory.Exists(Common.fsPath) Then
            MessageBox.Show("Please select exchange public folder")
            Exit Sub
        End If
        If treeSP.SelectedNode Is Nothing Then
            MessageBox.Show("Please select sharepoint location")
            Exit Sub
        End If

        PictureBox1.Visible = True
        BackWorker = New System.ComponentModel.BackgroundWorker()
        Dim dicParameters As Dictionary(Of String, String) = New Dictionary(Of String, String)
        dicParameters.Add("URL", txtSPURL.Text)
        dicParameters.Add("CurrentNodePath", treeSP.SelectedNode.Tag)
        dicParameters.Add("ParentNodePath", treeSP.SelectedNode.Parent.Tag)
        BackWorker.RunWorkerAsync(dicParameters)
    End Sub
    Private Sub btnAddMetaData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddMetaData.Click
        SaveDocumentInTempFolder()
        If Not Directory.Exists(Common.fsPath) Then
            MessageBox.Show("Please select an exchange public folder")
            Exit Sub
        End If

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

        Dim frm As New AddMetaData()
        frm.Show()
    End Sub
    Private Sub BackWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackWorker.DoWork
        Dim dicParameters As Dictionary(Of String, String) = CType(e.Argument, Dictionary(Of String, String))
        Common.UploadFiles(dicParameters)
        'Delete Temp Files...
        'Common.DeleteFolder(Common.fsPath)
    End Sub
    Private Sub BackWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackWorker.RunWorkerCompleted
        PictureBox1.Visible = False
        MessageBox.Show("Documents migrated successfully.")
    End Sub
    Private Sub Migration_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim strURL As String
        Dim sUserID As String
        Dim sPassword As String
        strURL = txtExchangePath.Text
        sUserID = txtExchnageUserName.Text
        sPassword = txtExchnagePassword.Text
        treeExPublicFolder.Nodes.Clear()
        If strURL <> "" And sUserID <> "" And sPassword <> "" Then
            ListFolders(strURL, sUserID, sPassword)
        End If
    End Sub
    Private Sub btnBrowseFolder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowseFolder.Click

        If txtExchangePath.Text = "" Then
            MsgBox("Please enter Exchange public folder path")
            Exit Sub
        End If

        If txtExchnageUserName.Text = "" Then
            MsgBox("Please enter Exchange Server User Name")
            Exit Sub
        End If

        If txtExchnagePassword.Text = "" Then
            MsgBox("Please enter Exchange Server Password")
            Exit Sub
        End If
        Dim strURL As String
        Dim sUserID As String
        Dim sPassword As String
        strURL = txtExchangePath.Text 'http://192.168.50.1/public/
        sUserID = txtExchnageUserName.Text ' angna 
        sPassword = txtExchnagePassword.Text ' test@1234
        treeExPublicFolder.Nodes.Clear()
        ListFolders(strURL, sUserID, sPassword)
    End Sub

#End Region
#Region "Functions"
    Private Sub SaveDocumentInTempFolder()
        Dim strFolder As String
        Dim sPathName As String
        For i As Integer = 0 To alCheckedExMailFolders.Count - 1
            strFolder = txtExchangePath.Text.Trim() & alCheckedExMailFolders.Item(i).ToString()

            sPathName = fsPath & alCheckedExMailFolders.Item(i).ToString() & "\"
            sPathName = sPathName.Replace("/", "\")

            Dim diSource As DirectoryInfo = New DirectoryInfo(sPathName)
            If (diSource.Exists) Then
                For Each fi As FileInfo In diSource.GetFiles()
                    fi.Delete()
                Next fi
                diSource.Delete()
            End If
            CreateFolder(sPathName)
            SavePublicFolderAttachments(strFolder, sPathName)
        Next
    End Sub
    Private Sub SavePublicFolderAttachments(ByVal sUri As String, ByVal sFileName As String)
        Dim xmlhttp As New MSXML.XMLHTTPRequest

        Dim oDoc As MSXML.DOMDocument
        Dim oDocBack As MSXML.DOMDocument

        Dim oNode As IXMLDOMElement
        Dim oNode2 As IXMLDOMElement

        Dim strQuery As String
        Dim query As MSXML.IXMLDOMText

        Dim pi As MSXML.IXMLDOMProcessingInstruction

        oDoc = CreateObject("MSXML2.DomDocument.6.0")
        oDocBack = CreateObject("MSXML2.DomDocument.6.0")

        oDoc = CreateObject("MICROSOFT.XMLDOM")
        oDocBack = CreateObject("MICROSOFT.XMLDOM")
        pi = oDoc.createProcessingInstruction("xml", "version=""1.0""")
        oDoc.appendChild(pi)

        oNode = oDoc.createNode(1, "searchrequest", "DAV:")
        oDoc.documentElement = oNode

        oNode2 = oDoc.createNode(1, "sql", "DAV:")
        oNode.appendChild(oNode2)

        strQuery = "SELECT ""DAV:displayname"", ""DAV:contentclass"",""DAV:body"", ""DAV:href"", ""DAV:hassubs"",""urn:schemas:httpmail:subject"",""urn:schemas:httpmail:textdescription"",""urn:schemas:httpmail:fromemail"",""urn:schemas:httpmail:hasattachment"",""urn:schemas:httpmail:attachmentfilename"""
        strQuery = strQuery & " FROM SCOPE('shallow traversal of """ & sUri & """')"
        strQuery = strQuery & " ORDER BY ""DAV:displayname"""
        query = oDoc.createTextNode(strQuery)
        oNode2.appendChild(query)

        xmlhttp = CreateObject("microsoft.xmlhttp")
        xmlhttp.open("SEARCH", sUri, False, txtExchnageUserName.Text.Trim(), txtExchnagePassword.Text.Trim())
        xmlhttp.setRequestHeader("Translate", "f")
        xmlhttp.setRequestHeader("Content-Type", "text/xml")
        xmlhttp.setRequestHeader("Depth", "0")
        xmlhttp.send(oDoc)

        Dim xmlstr As Object = xmlhttp.responseXML
        Dim mails As Object = xmlstr.getElementsByTagName("a:response")
        Dim i As Integer
        Dim z As Integer
        z = 1
        Dim flg As Boolean
        flg = False
        For i = 0 To mails.length - 1
            Dim m_subject As Object = mails(i).getElementsByTagName("d:subject")
            If m_subject.length <> 0 Then
                Dim m_body As Object = mails(i).getElementsByTagName("a:displayname")
                Dim m_sender As Object = mails(i).getElementsByTagName("d:fromemail")
                Dim m_eml As Object = mails(i).getElementsByTagName("a:href")
                Dim atch As Object = mails(i).getElementsByTagName("d:hasattachment")
                Dim atch_flg As String = "1"
                Dim j As Integer
                For j = 0 To m_body.length - 1
                    If m_body.ToString() = m_subject.ToString() Then
                        m_body = m_body(j).firstChild.data()
                        atch_flg = atch.ToString()
                        If atch_flg.ToString().ToUpper() = atch.ToString().ToUpper() Then
                            Dim Mailname As String = sUri & "/" & m_body
                            Dim strResult As String
                            Dim HttpWebRequest As MSXML2.XMLHTTP40 = Nothing
                            HttpWebRequest = New MSXML2.XMLHTTP40()
                            HttpWebRequest.open("GET", Mailname, False, txtExchnageUserName.Text, txtExchnagePassword.Text)
                            HttpWebRequest.send("")
                            strResult = HttpWebRequest.responseText
                            Dim fname As String = m_body.ToString()
                            If (File.Exists(sFileName & fname)) Then
                                fname = fname & z
                                z = z + 1
                            End If
                            Try
                                Dim wcClient = New System.Net.WebClient
                                wcClient.Credentials = New System.Net.NetworkCredential(txtExchnageUserName.Text, txtExchnagePassword.Text)
                                If (Path.GetExtension(sFileName & fname) <> "") Then
                                    wcClient.DownloadFile(Mailname, sFileName & fname)
                                End If
                            Catch ex As System.Exception
                                Dim message As String = ""
                                message += ("Description : Cannot download File '" & fname & "'.")
                                'WriteLogFile("Migration", "Download from Exchnage", strMsg)
                                Try
                                    If message <> "" Then
                                        Using file As New FileStream(System.Windows.Forms.Application.StartupPath & "\Log.txt", FileMode.OpenOrCreate, FileAccess.Write)
                                            flg = True
                                            Dim streamWriter As New StreamWriter(file)
                                            streamWriter.WriteLine((((System.DateTime.Now & " - ") + "Migration" & " - ") + "Download from Exchnage" & " - ") + message)
                                            streamWriter.Close()
                                        End Using
                                    End If
                                Catch
                                End Try
                            Finally
                                If flg = True And i = mails.length - 1 Then
                                    MsgBox("Please view log for errors: " & System.Windows.Forms.Application.StartupPath & "\Log.txt")
                                End If
                            End Try
                        End If
                    End If
                Next
            End If
        Next
    End Sub
    Private Sub CreateFolder(ByVal FolderPath As String)
        ' Check if Folder Request already exists
        If System.IO.Directory.Exists(FolderPath) = False Then
            ' If not then create that folder
            System.IO.Directory.CreateDirectory(FolderPath)
        End If
    End Sub
    Private Sub FillSubWeb(ByVal tn As TreeNode, ByVal webSite As SPWeb)
        Dim theweb As SPWeb
        For Each theweb In webSite.Webs

            Dim subTN As TreeNode = New TreeNode(theweb.Title)
            subTN.ImageIndex = 1
            subTN.SelectedImageIndex = 1
            subTN.Tag = theweb.ServerRelativeUrl

            tn.Nodes.Add(subTN)
            'add code here to iterate on LISTS of theweb object. 

            FillList(subTN, theweb)

            FillSubWeb(subTN, theweb)
            theweb.Dispose()
        Next
    End Sub
    Private Sub FillList(ByVal tn As TreeNode, ByVal webSite As SPWeb)
        Dim thelist As SPList
        For Each thelist In webSite.Lists
            Dim ListTN As TreeNode = New TreeNode(thelist.Title)
            Dim logourl As String = thelist.ImageUrl
            Dim arraurl() As String = logourl.Split("/")
            ListTN.SelectedImageKey = arraurl(arraurl.Length - 1)
            ListTN.ImageKey = arraurl(arraurl.Length - 1)
            ListTN.Tag = thelist.Title
            tn.Nodes.Add(ListTN)

        Next
    End Sub
    Sub ListFolders(ByVal strURL As String, ByVal sUserID As String, _
ByVal sPassword As String)
        Dim oDoc As MSXML.DOMDocument
        Dim oDocBack As MSXML.DOMDocument

        Dim oNode As IXMLDOMElement
        Dim oNode2 As IXMLDOMElement
        Dim req As MSXML.XMLHTTPRequest

        Dim strQuery As String
        Dim query As MSXML.IXMLDOMText

        Dim pi As MSXML.IXMLDOMProcessingInstruction
        Dim objNode As Object

        oDoc = CreateObject("MSXML2.DomDocument.6.0")
        oDocBack = CreateObject("MSXML2.DomDocument.6.0")

        oDoc = CreateObject("MICROSOFT.XMLDOM")
        oDocBack = CreateObject("MICROSOFT.XMLDOM")
        pi = oDoc.createProcessingInstruction("xml", "version=""1.0""")
        oDoc.appendChild(pi)

        oNode = oDoc.createNode(1, "searchrequest", "DAV:")
        oDoc.documentElement = oNode

        oNode2 = oDoc.createNode(1, "sql", "DAV:")
        oNode.appendChild(oNode2)
        'strQuery = "Select ""DAV:displayname"" From "
        'strQuery = strQuery & "Scope('Shallow Traversal of """ & strURL & """')"
        strQuery = "SELECT ""DAV:displayname"", ""DAV:contentclass"", ""DAV:href"", ""DAV:hassubs"""
        strQuery = strQuery & " FROM SCOPE('shallow traversal of """ & strURL & """')"
        strQuery = strQuery & " WHERE ""DAV:isfolder"" = True AND "
        strQuery = strQuery & """DAV:ishidden"" = False"
        strQuery = strQuery & " ORDER BY ""DAV:displayname"""
        query = oDoc.createTextNode(strQuery)
        oNode2.appendChild(query)

        req = CreateObject("microsoft.xmlhttp")
        req.open("SEARCH", strURL, False, sUserID, sPassword)
        req.setRequestHeader("Translate", "f")
        req.setRequestHeader("Content-Type", "text/xml")
        req.setRequestHeader("Depth", "0")
        req.send(oDoc)

        oDocBack = req.responseXML

        Dim objNodeList As Object

        'Typically the DAV namespace get the 'a' prefix.
        'If you are specifying multiple properties in a search, examine the 
        'returned XML befo-rehand to determine prefixes for your code.

        objNodeList = oDocBack.getElementsByTagName("a:displayname")
        'treeExPublicFolder.Nodes.Clear()
        For i = 0 To (objNodeList.Length - 1)
            objNode = objNodeList.nextNode
            If (objNode Is Nothing) Then
            Else
                Debug.Print(objNode.Text)
                If (i > 1) Then
                    treeExPublicFolder.Nodes(0).TreeView.CheckBoxes = True
                End If
                treeExPublicFolder.Nodes.Add(objNode.Text, objNode.Text)
                ListFoldersSub(strURL & "/" & objNode.Text, sUserID, sPassword, i)
            End If
        Next
    End Sub
    Sub ListFoldersSub(ByVal strURL As String, ByVal sUserID As String, _
ByVal sPassword As String, ByVal index As Integer)
        Dim oDoc As MSXML.DOMDocument
        Dim oDocBack As MSXML.DOMDocument

        Dim oNode As IXMLDOMElement
        Dim oNode2 As IXMLDOMElement
        Dim req As MSXML.XMLHTTPRequest

        Dim strQuery As String
        Dim query As MSXML.IXMLDOMText

        Dim pi As MSXML.IXMLDOMProcessingInstruction
        Dim objNode As Object

        oDoc = CreateObject("MSXML2.DomDocument.6.0")
        oDocBack = CreateObject("MSXML2.DomDocument.6.0")

        oDoc = CreateObject("MICROSOFT.XMLDOM")
        oDocBack = CreateObject("MICROSOFT.XMLDOM")
        pi = oDoc.createProcessingInstruction("xml", "version=""1.0""")
        oDoc.appendChild(pi)

        oNode = oDoc.createNode(1, "searchrequest", "DAV:")
        oDoc.documentElement = oNode

        oNode2 = oDoc.createNode(1, "sql", "DAV:")
        oNode.appendChild(oNode2)
        'strQuery = "Select ""DAV:displayname"" From "
        'strQuery = strQuery & "Scope('Shallow Traversal of """ & strURL & """')"
        strQuery = "SELECT ""DAV:displayname"", ""DAV:contentclass"", ""DAV:href"", ""DAV:hassubs"""
        strQuery = strQuery & " FROM SCOPE('shallow traversal of """ & strURL & """')"
        strQuery = strQuery & " WHERE ""DAV:isfolder"" = True AND "
        strQuery = strQuery & """DAV:ishidden"" = False"
        strQuery = strQuery & " ORDER BY ""DAV:displayname"""
        query = oDoc.createTextNode(strQuery)
        oNode2.appendChild(query)

        req = CreateObject("microsoft.xmlhttp")
        req.open("SEARCH", strURL, False, sUserID, sPassword)
        req.setRequestHeader("Translate", "f")
        req.setRequestHeader("Content-Type", "text/xml")
        req.setRequestHeader("Depth", "0")
        req.send(oDoc)

        oDocBack = req.responseXML

        Dim objNodeList As Object

        'Typically the DAV namespace get the 'a' prefix.
        'If you are specifying multiple properties in a search, examine the 
        'returned XML befo-rehand to determine prefixes for your code.

        objNodeList = oDocBack.getElementsByTagName("a:displayname")
        'treeExPublicFolder.Nodes.Clear()
        For i = 0 To (objNodeList.Length - 1)
            objNode = objNodeList.nextNode
            If (objNode Is Nothing) Then
            Else
                Debug.Print(objNode.Text)
                treeExPublicFolder.Nodes(index).TreeView.CheckBoxes = True
                treeExPublicFolder.Nodes(index).Nodes.Add(objNode.Text, objNode.Text)
                ListFoldersSub(strURL & "/" & objNode.Text, sUserID, sPassword, index)
            End If
        Next
    End Sub
#End Region

   
End Class
