,

Background File Transfer Sample Code

The sample for this chapter continues from where we left off in Chapter 32, “Conducting Background Activities with Scheduled Actions.” This chapter looks at backing up the to-do items database to a remote server using WCF.

Within the BackgroundAgents solution in the downloadable sample code is a project named WPUnleashed.BackgroundAgents.Web. This project exposes a WCF service named BackupService, which allows the phone app to save files to the Backups directory on the server by way of its SaveFile method (see Listing 33.1). The SaveFile method accepts a Stream, which is written to a file on the server. The unique ID of the user is also sent to the server to allow correct retrieval of the file at a later time.

LISTING 33.1. BackupService Class


[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
[AspNetCompatibilityRequirements(
    RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class BackupService : IBackupService
{
    public void SaveFile(string userId, string fileName, Stream fileStream)
    {
        string location = string.Format(
                             @"~Backups{0}_{1}", userId, fileName);
        var filepath = HttpContext.Current.Server.MapPath(location);
        using (Stream outputStream = File.OpenWrite(filepath))
        {
            CopyStream(fileStream, outputStream);
        }
    }

    static void CopyStream(Stream input, Stream output)
    {
        var buffer = new byte[8 * 1024];
        int streamLength;

        while ((streamLength = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, streamLength);
        }
    }
}


There is no retrieval method in the WCF service because an ordinary HTTP GET request is used to download the file.

The WPUnleashed.BackgroundAgents contains a web reference to the WPUnleashed.BackgroundAgents.Web project, and the service is consumed within the TodoListViewModel class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.192.247