views:

365

answers:

1

Hi,

I want to import records from csv file to the DB from Silverlight front end. I am using WCF service to perform the DB operations. When I pass the entire file path (hard coded), I am able to add records to the DB, but as OpenFileDialog in Silverlight doesn't allow to obtain the file path's (due to security reasons), I tried using WCF service and pass either the FileInfo property or StreamReader and then perform the operations. But its giving me an exception. I have the following code -

1) Passing StreamReader Page.xaml.vb file

Dim service As New ServiceReference1.Service1Client
dlg.ShowDialog()
Dim Reader As System.IO.StreamReader
If dlg.File IsNot Nothing Then
   Reader = dlg.File.OpenText
End If
service.ImportPersonInfoAsync(Reader)

'Service1.svc.vb file

<OperationContract()> _
    Public Sub ImportPersonInfo(ByVal Reader As System.IO.StreamReader)
    'Code to add records to DB table
    End Sub

I am getting an exception - The remote server returned an error: NotFound (in EndInvoke method)

Public Sub EndImportPersonInfo(ByVal result As System.IAsyncResult) Implements ServiceReference1.Service1.EndImportPersonInfo
    Dim _args((0) - 1) As Object
    MyBase.EndInvoke("ImportPersonInfo", _args, result)
End Sub

2) Passing FileInfo

Page.xaml.vb file

If dlg.File IsNot Nothing Then
   ImportFile = dlg.File
End If
service.ImportPersonInfoAsync(ImportFile)

Service1.svc.vb file

Public Sub ImportPersonInfo(ByVal ImportFile As System.IO.FileInfo)
    Dim Reader As System.IO.StreamReader = ImportFile.OpenText
    'Do operation
End Sub

I am getting an exception in BeginInvoke method - Attempt to access the method failed: System.IO.FileSystemInfo.get_Attributes()

Can anyone please help me out / suggest solution or a better approach to import records from csv into the DB programmatic using Silverlight.

Thanks!

A: 

Neither FileInfo nor StreamReader are serializable classes, so you can't really pass them directly to the server with WCF. An option is to read the file in memory, then pass it to the service, something like shown below. Another option is read the .csv file in multiple lines (List) and pass it to the service.

Dim service As New ServiceReference1.Service1
Clientdlg.ShowDialog()
Dim ms As System.IO.MemoryStream
If dlg.File IsNot Nothing Then
   Dim TheFile as Stream = dlg.File.OpenRead()
   Dim Buffer as Byte() = New Byte(10000) { }
   Dim BytesRead as Integer
   Do
      BytesRead = TheFile.Read(Buffer, 0, Buffer.Length)
      ms.Write(Buffer, 0, BytesRead)
   Loop While (BytesRead > 0)
End If
TextEnd Ifservice.ImportPersonInfoAsync(ms.ToArray())
Thanks Carlos, that did give me a direction. I worked on it and it seemed to work fine. Now I have changed the way it works, I am first uploading a file to the server, and then using it to import records. Thanks for suggesting and sorry for replying late.
Vishal