Использование веб-службы REST для получения папок и файлов из XML-документа - PullRequest
0 голосов
/ 01 мая 2018

В настоящее время я пытаюсь создать веб-интерфейс, который будет принимать заказ на продажу # и вызывать веб-службу REST для подключения нашей БД и получения объекта Sharepoint, который будет сериализован в XML. Я новичок в веб-службах, поэтому я не уверен, что именно делать, особенно потому, что большинство примеров, которые я вижу, они извлекают строки, и я даже не уверен, что вы можете извлечь файлы или папки. Опять же, новичок в этом.

Есть ли способ получить папки и файлы из XML? Я сделал этот проект как приложение для Windows Form в надежде получить информацию, чтобы получить представление в виде дерева, но безуспешно. Было бы лучше сделать это приложение WCF? Любой совет будет полезен

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

1 Ответ

0 голосов
/ 02 мая 2018

Ваш запрос немного сбивает с толку. Приведенный ниже код извлекает имена файлов и папок и помещает результаты в файл XML. Может быть, это поможет:

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;

        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...