0

I'm currently trying to build a web interface that will take in a Sales Order # and call a REST Web Service to connect our DB and get a Sharepoint object which will be serialized into XML. I'm new to Web Services so I'm not sure what exactly to do especially since most of the examples I see, they're retrieving Strings and I'm not even sure you can retrieve files or folders. Again, new to this.

Is there a way to get the folders and files from the XML? I made this project as a Windows Form App in hopes of getting the info to pull into a treeview but no success. Would it be a better idea to make this a WCF Application? Any advice would be helpful

Imports System.Data.SqlClient
Imports MagnetExchangeUtilities
Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization
Imports MagnetExchangeUtilities.Sharepoint

Public Class Form1
Dim ex As Sharepoint = Nothing
Const connectionString As String = "Server=SQL1;Database=MGNET;Trusted_Connection=True;Connection Timeout=120"
Dim retValue As ReturnVal
'Dim email As EmailItem
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


    If tbOrderRef.Text = "" Then
        MsgBox("Please enter Order Ref")
        Exit Sub
    End If
    Dim Ref = tbOrderRef.Text
    retValue = GetOrderInformation(Ref)


    ex = New Sharepoint()



    Dim t = ex.GetOrderContent(retValue.Year, retValue.SONumber)

    Dim myT = New SPFolderOver()
    myT = SPFolderOver.LoadFolder(t)
    myT.Name = t.Name

    SerializeObjectToFile(myT, "C:\Users\apearson\Documents\Works.xml")





End Sub

Public Sub SerializeObjectToFile(Of T)(serializableObject As T, fileName As String)
    'Throws exception if the object is null
    If serializableObject Is Nothing Then
        Throw New Exception("The value of the passed object does not contain a value.")
    End If

    Try
        'instantiate xmlDocument
        Dim xmlDocument As New XmlDocument()
        'Create serializer with the type of the the serializableObject passed as a parameter
        Dim serializer As New XmlSerializer(serializableObject.[GetType]())
        'Create MemoryStream to write the serialized data to memory
        Using stream As New MemoryStream()
            'Pass the serialized data to the writer
            serializer.Serialize(stream, serializableObject)
            'Double check that the memory stream position is zero
            stream.Position = 0
            'Load string held in writer into the XMLDocument
            xmlDocument.Load(stream)
            'Save populated XMLDocument to the file path passed as a parameter
            xmlDocument.Save(fileName)
            stream.Close()
        End Using
        'Log exception here
    Catch ex As Exception
        Throw New Exception(ex.ToString)
    End Try
End Sub

Private Function GetOrderInformation(ByVal OrderRef As String) As ReturnVal
    Dim SONumber As String = ""
    Dim OrderYear As String = ""
    Dim SQlText As String = "SELECT top 1 msoh.SONumber,  year(soorderdate)" & Environment.NewLine & _
"  FROM [MGNET].[dbo].[MagSalesOrderCommitedItems] msoci" & Environment.NewLine & _
"  inner join MagSalesOrderHeader msoh on msoh.sonumber = msoci.SONumber" & Environment.NewLine & _
"  where msoh.SONumber = '" & OrderRef & "'" & Environment.NewLine & _
"union all" & Environment.NewLine & _
"SELECT top 1 msoh.SONumber,  year(soorderdate)" & Environment.NewLine & _
"  FROM [MGNET].[dbo].[MagSalesOrderCommitedItems] msoci" & Environment.NewLine & _
"  inner join MagSalesOrderHeader msoh on msoh.sonumber = msoci.SONumber" & Environment.NewLine & _
"  where msoci.SOQuoteNumber = '" & OrderRef & "'"


    Using con = New SqlConnection(connectionString)

        Using cmd = New SqlCommand(SQlText, con)

            Try
                con.Open()
            Catch ex As Exception
                Throw New Exception("Error opening connection")
            End Try

            Using rdr = cmd.ExecuteReader

                If rdr.HasRows Then
                    While rdr.Read()
                        SONumber = rdr(0)
                        OrderYear = rdr(1)
                    End While
                End If
            End Using
        End Using
    End Using
    Dim ret = New ReturnVal

    ret.SONumber = SONumber
    ret.Year = OrderYear
    Return ret
End Function

Private Sub tvInfo_NodeMouseClick(sender As Object, e As TreeNodeMouseClickEventArgs) Handles tvInfo.NodeMouseClick

End Sub

Private Sub tvInfo_NodeMouseDoubleClick(sender As Object, e As TreeNodeMouseClickEventArgs) Handles tvInfo.NodeMouseDoubleClick
    Dim node = tvInfo.SelectedNode
    Dim subFolder As String = node.Parent.Text
    Dim fileName = ex.GetFileContent(retValue.Year, retValue.SONumber, subFolder, node.Text.Split(";").First.Trim)
    Process.Start(fileName)
End Sub
End Class

Public Class ReturnVal
Public Property SONumber As String
Public Property Year As String
End Class



Public Class SPFolderOver
Private _files As List(Of SPFile)
Private _folders As List(Of SPFolderOver)
Private _name As String
Private _fullPath As String

'Private _folderObj As Object
'Private _ctx As SP.ClientContext
Private _sp As Sharepoint



Public Shared Function LoadFolder(ByVal t As SPFolder) As SPFolderOver
    Dim spFolder = New SPFolderOver
    spFolder.SPFolders = New List(Of SPFolderOver)
    For Each f In t.SPFolders
        Dim spFold = New SPFolderOver
        spFold.FullPath = f.FullPath
        spFold.SPFiles.AddRange(f.SPFiles)
        If t.SPFolders.Count > 0 Then
            spFold.SPFolders = New List(Of SPFolderOver)

            For Each nf In f.SPFolders

                spFold.SPFolders.Add(LoadFolder(nf))
            Next
        End If
        spFolder.SPFolders.Add(spFold)
    Next
    Return spFolder
End Function
Public Property SPFiles() As List(Of SPFile)
    Get
        Return _files
    End Get
    Set(ByVal value As List(Of SPFile))
        _files = value
    End Set
End Property
Public Property SPFolders() As List(Of SPFolderOver)
    Get
        Return _folders
    End Get
    Set(ByVal value As List(Of SPFolderOver))
        _folders = value
    End Set
End Property
Public Property Name() As String
    Get
        Return _name
    End Get
    Set(ByVal value As String)
        _name = value
    End Set
End Property

Public Property Folder() As Object
    Get
        'Return _folderObj
        Return Nothing
    End Get
    Set(ByVal value As Object)
        '_folderObj = value
    End Set
End Property
'Public Property SPContext() As SP.ClientContext
'    Get
'        'Return _ctx
'        Return Nothing
'    End Get
'    Set(ByVal value As SP.ClientContext)
'        '_ctx = value
'    End Set
'End Property
Public Property FullPath() As String
    Get
        Return _fullPath
    End Get
    Set(ByVal value As String)
        _fullPath = value
    End Set
End Property
Public Property SP() As Sharepoint
    Get
        Return _sp
    End Get
    Set(ByVal value As Sharepoint)
        _sp = value
    End Set
End Property


Public Sub New()
    _files = New List(Of SPFile)
    _folders = New List(Of SPFolderOver)

    '_folderObj = Nothing
    _sp = Nothing
End Sub
Public Sub Delete()
    'If _folderObj Is Nothing Then
    'Return
    'End If
    'Try
    '    _folderObj.DeleteObject()
    '    _ctx.ExecuteQuery()
    'Catch ex As Exception
    '    Throw New Exception("Unable to delete folder! Message: " & ex.Message, ex)
    'End Try
    Try
        '_sp.Impersonation.Impersonate(_sp.Credentials)
        Directory.Delete(_fullPath, True)
    Catch ex As Exception
        Throw New Exception("Unable to delete folder! Message: " & ex.Message, ex)
        'Finally
        '_sp.Impersonation.Undo()
    End Try
End Sub
End Class
  • XML represents data structures so you could use it to represent yours regardless of whether they are files or folders. – LMC May 01 '18 at 23:47

1 Answers1

0

You request is a little confusing. The code below extracts the names of files and folders and puts results into an xml file. Maybe this will help :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace SAveDirectoriesXml
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        const string FOLDER = @"c:\temp";
        static XmlWriter writer = null;
        static void Main(string[] args)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;

            writer = XmlWriter.Create(FILENAME, settings);
            writer.WriteStartDocument(true);

            DirectoryInfo info = new DirectoryInfo(FOLDER);
            WriteTree(info);

            writer.WriteEndDocument();
            writer.Flush();
            writer.Close();
            Console.WriteLine("Enter Return");
            Console.ReadLine();

        }
        static long WriteTree(DirectoryInfo info)
        {
            long size = 0;
            writer.WriteStartElement("Folder");
            try
            {
                writer.WriteAttributeString("name", info.Name);
                writer.WriteAttributeString("numberSubFolders", info.GetDirectories().Count().ToString());
                writer.WriteAttributeString("numberFiles", info.GetFiles().Count().ToString());
                writer.WriteAttributeString("date", info.LastWriteTime.ToString());


                foreach (DirectoryInfo childInfo in info.GetDirectories())
                {
                    size += WriteTree(childInfo);
                }

            }
            catch (Exception ex)
            {
                string errorMsg = string.Format("Exception Folder : {0}, Error : {1}", info.FullName, ex.Message);
                Console.WriteLine(errorMsg);
                writer.WriteElementString("Error", errorMsg);
            }

            FileInfo[] fileInfo = null;
            try
            {
                fileInfo = info.GetFiles();
            }
            catch (Exception ex)
            {
                string errorMsg = string.Format("Exception FileInfo : {0}, Error : {1}", info.FullName, ex.Message);
                Console.WriteLine(errorMsg);
                writer.WriteElementString("Error",errorMsg);
            }

            if (fileInfo != null)
            {
                foreach (FileInfo finfo in fileInfo)
                {
                    try
                    {
                        writer.WriteStartElement("File");
                        writer.WriteAttributeString("name", finfo.Name);
                        writer.WriteAttributeString("size", finfo.Length.ToString());
                        writer.WriteAttributeString("date", info.LastWriteTime.ToString());
                        writer.WriteEndElement();
                        size += finfo.Length;
                    }
                    catch (Exception ex)
                    {
                        string errorMsg = string.Format("Exception File : {0}, Error : {1}", finfo.FullName, ex.Message);
                        Console.WriteLine(errorMsg);
                        writer.WriteElementString("Error", errorMsg);
                    }
                }
            }

            writer.WriteElementString("size", size.ToString());
            writer.WriteEndElement();
            return size;

        }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20
  • Sorry that the question is all over the place. I wasn't really given a good direction on this and I've asked questions to my boss but not really getting a clear answer. The overall function of the web service is to take an order # and retrieve the folders and files pertaining to it. The customers should be able to look at them and then add files to the artwork folder that is with them. I think the issue I'm trying to fix is whether I can actually get access to those files from the XML that comes back if that makes sense. – the1APerson May 02 '18 at 20:58
  • You response still has issues. You say : "take an order # and retrieve the folders and files pertaining to it". So does this mean that you are just doing a directory of the files that came back, or are you opening the files and reading the files? It kind of sounds like there is are filenames in at least one file the is returned. – jdweng May 03 '18 at 06:53
  • The customer should be allowed to open and read the files, yes. My boss wants it so it appears as a directory or a treeview. – the1APerson May 03 '18 at 14:40
  • Then see following recursive reading of xml into a treeview. Rerefer people to this posting all the time : https://stackoverflow.com/questions/28976601/recursion-parsing-xml-file-with-attributes-into-treeview-c-sharp – jdweng May 03 '18 at 15:10