Click here to Skip to main content
Click here to Skip to main content

SharpBITS.NET - A Wrapper for the BITS API

By , 7 Oct 2010
 

Sharpbits.NET - Winforms application based on the wrapper library

Introduction

SharpBITS is a library to wrap the BITS SDK for use with managed code on the .NET platform. It was intended and first implemented for a project designed to transfer large files over a slow and unstable WAN link. While there are some other options like use of FTP, BITS had some real advantages that made it the favorite selection.

As it uses the HTTP/HTTPS protocol to transfer files, it is immune to firewall restrictions. Also, it keeps a session (in default setting) for up to 14 days, which gives a reliable file transfer option in this case! The project where SharpBITS was developed consists of a small command line application, and the separate BITS wrapper library. Even if there are some custom implementations for the BITS wrapper available already, also for .NET managed code (see "Wrapping Bits" on MSDN), they are based on older versions of BITS and don't support some features like authentication, so the decision was to have a new C# based wrapper library.

Background

Background Intelligent Transfer Service (BITS) can be used to transfer (large) files asynchronously between a client and a server. Background transfers are optimal in that BITS uses idle network bandwidth to transfer the files, and can increase or decrease the rate at which files are transferred based on the amount of idle network bandwidth available. If a network application begins to consume more bandwidth, BITS decreases its transfer rate to preserve the user's interactive experience. BITS continues to transfer files after an application exits if the user who initiated the transfer remains logged on and a network connection is maintained. BITS suspends the transfer if a connection is lost or if the user logs off. BITS persists transfer information while the user is logged off, across network disconnects, and during computer restarts.

The complete description and documentation on BITS can be found on MSDN.

Requirements

For using BITS, the following requirements must be met:

Client

On the client side, Windows 2000 SP3 or later is required and the BITS service must be running. BITS is also supported on Windows Vista and Longhorn Server (with upcoming new features like P2P-functionality).

Windows 95/98/ME/NT are not supported.

Server

For uploads, BITS requires IIS 5.0 on Windows 2000 Server, and IIS 6.0 on Windows Server 2003 family; BITS does not support IIS 5.1 on Windows XP.

Using the code

All you have to do for getting started with SharpBITS is to create an instance of BitsManager. BitsManager is the single instance giving access to create a new job or list existing jobs.

To create a new job, the code looks as simple as that:

BitsManager manager = new BitsManager();
manager.EnumJobs(JobOwner.CurrentUser);

// populate current job list first
BitsJob job = manager.CreateJob("TestJob", JobType.Download);
job.AddFile("http://localhost/bits/mydownload.cab", "C:\\temp\\download.cab");
job.Resume();

Also, it is very simple to iterate through all existing jobs and list their properties. Each job has various properties like name, owner, priority, and of course, a list of files to transfer. (While a download job can have multiple files to transfer, an upload job is restricted to one file per job!)

manager.EnumJobs(JobOwner.CurrentUser);     
// list either all jobs or for current user only
System.Console.WriteLine("Job Count for current user: {0}", 
                manager.Jobs.Count.ToString());
foreach (BitsJob job in manager.Jobs.Values)
{
    System.Console.WriteLine("Displayname for job: {0}", job.DisplayName);
    System.Console.WriteLine("Owner: {0}", job.Owner);
    System.Console.WriteLine("Priority: {0}", job.Priority.ToString());
    job.EnumFiles();
    System.Console.WriteLine("File Count for current job: {0}", 
                    job.Files.Count.ToString());
    foreach (BitsFile file in job.Files)
    {
        System.Console.WriteLine("Local File Name: {0}", file.LocalName);
        System.Console.WriteLine("Remote File Name: {0}", file.RemoteName);
        System.Console.WriteLine("Bytes total: {0}", 
            file.Progress.BytesTotal.ToString());
        System.Console.WriteLine("Bytes transfered: {0}", 
            file.Progress.BytesTransferred.ToString());
    }
    System.Console.WriteLine("Job State: {0}", job.State.ToString());
    System.Console.WriteLine("Job Type: {0}", job.JobType.ToString());
}

Instead of polling for the status of a job all the time, BITS enables to set a callback pointer for the notification interface. In SharpBITS, this callback handling is wrapped to .NET events. There are three different kinds of events, raised if job is modified, completed, or if an error has occurred. The JobModifiedEvent event will also be fired if the JobProgress or FileProgress for a job is updated, so this can be used to display a job progress.

Event handlers can be attached to either a job to get events for that particular job only, or to the BitsManager to catch all events. Even for those, you have to set the kind of events fired for each particular job.

//Set flags to get notified on Job Completed or Job Error event
job.NotificationFlags = 
    NotificationFlags.JobTransferred | NotificationFlags.JobErrorOccured;
//never raised with the previous flags
job.OnJobModifiedEvent += 
    new EventHandler<JOBNOTIFICATIONEVENTARGS>(job_OnJobModifiedEvent);

Credits

The interop handling in this library is based on some implementations from the "Microsoft Updater Application Block for .NET" (http://msdn2.microsoft.com/en-us/library/ms978574.aspx), which is part of the Enterprise Library.

Conclusion

As it seems, BITS can be used to fulfill various requirements for transferring files in a reliable manner, and is somewhat underestimated currently. I started to develop a Windows Forms application also (where the above screenshot was taken from). This application development is still in progress, but a running version and more details (source code as well) can be found on the SharpBITS.NET homepage.

History

  • 07/09/2006: Posted to CodeProject.
  • 10/10/2006: Update posted to CodeProject.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

xidar
Svalbard And Jan Mayen Svalbard And Jan Mayen
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
AnswerRe: com visible?memberxidar24 Nov '08 - 4:33 
It should work from VB6 as well via COM, but I don't have a sample yet.
However, I wonder if it's worth the overhead of encapsulating a COM to .NET to wrap into COM again... all of the functionality of BITS is available using the COM interfaces, should be pretty easy to use directly with VB
 
Comments in my code? Why do you think do they call it 'code' ??

QuestionUrgent: use sharp bits in windows servicememberMavei3 Nov '08 - 19:41 
i use sharp bits to download files from a web server, the server requires wondows authentication, it works good when i build the code as an application; but when i changed the code to ruan as a windows service(the service run as Local System), the bit job always reports some thing like that "...server resource requires auth..", my code as below:
BitsManager manager = new BitsManager();
manager.EnumJobs(JobOwner.CurrentUser);
BitsJob newJob = manager.CreateJob(jobName, JobType.Download);
//set authentication if server require it
BitsCredentials credit = new BitsCredentials();
credit.AuthenticationScheme = AuthenticationScheme.Negotiate;
credit.AuthenticationTarget = AuthenticationTarget.Server;
credit.UserName = "DownloadAuthenticationUserName";
credit.Password = "DownloadAuthenticationPassword";
newJob.AddCredentials(credit);
....
newJob.AddFile(remoteFn, localFn);
newJob.Resume();
...
 
i checked msdn about BITS: http://msdn.microsoft.com/en-us/library/aa363152(VS.85).aspx[^], but i don't understand.
 
Can anyone tell me how to run BITS with authentication in windows service?
thanks in advance.
 
Mavei mavei.ma@gmail.com
AnswerRe: Urgent: use sharp bits in windows servicememberxidar3 Nov '08 - 22:23 
have you tried AuthenticationScheme.NTLM?
 
This should be the right setting for windows authentication.
 
Comments in my code? Why do you think do they call it 'code' ??

GeneralRe: Urgent: use sharp bits in windows servicememberMavei3 Nov '08 - 23:20 
Yes, i tried and got the same error.
i event tried to let service running in an user acount, but all jobs are suspended(resume it and still suspended.).
 
any idea?
GeneralRe: Urgent: use sharp bits in windows servicememberBBiales3 Mar '09 - 6:32 
Perhaps you can setup the ID/PW the service will run as, rather than running as SYSTEM?
QuestionHow Upload?memberrbarzallo31 Oct '08 - 13:47 
Please, any sample for upload?
 
Grettings
AnswerRe: How Upload?memberxidar3 Nov '08 - 22:24 
it's same as for downloads, just set the JobType appropriate. Of course your server needs to be enabled for BITS uploads (IIS has some self explaining settings there).
 
Comments in my code? Why do you think do they call it 'code' ??

QuestionGet Job ID from OnJobCompleted?memberNiteBeast18 Sep '08 - 12:48 
When I create my OnJobCompleted event handler the EventArgs are for JobNotificationEventArgs which doesn't expose any way to attain the Job name or ID. NotificationEventArgs does expose a Job object though.
 
Is this an oversight or is there a way to get a job ID from JobNotificationEventArgs?
 
Thanks.
AnswerRe: Get Job ID from OnJobCompleted?memberxidar18 Sep '08 - 20:38 
as the event is tight to a particular job (actually you subscribe to myJob.OnJobCompleted event), you should know which job this was. If this is not sufficient, you can subscribe to similar event on the BitsManager instance, which passes an additional reference to the job the event was raised for.
 
Comments in my code? Why do you think do they call it 'code' ??

QuestionRe: Get Job ID from OnJobCompleted? [modified]memberNiteBeast19 Sep '08 - 4:45 
Wow, quick reply... awesome.
 
I'm going to need to add some reference to the calling job in the handler so I can call the Complete() method and update my Database. Currently I'm doing it through a hacked up messaging system that really isn't what I'd like to do.
 
I think I'll look at the BitsManager object events and use that.
 
Thanks again for getting back to me so fast. Smile | :)
 

Edit -
 
Well, I was having an issue and had written something here but I solved it. The BitsManager event was the solution.
 
modified on Friday, September 19, 2008 12:10 PM

QuestionResume download from web client.memberdotnetgoodman17 Jun '08 - 2:18 
Hi,
 
My requirement is that any authorised user can download relatively a large file from server through my web site.
So, i have to provide a resume later option for downloading.
Where in, if the user come again for the same page, i should alow him to download from the place where he left over.
 
Can i use BITS for this, or can somebody pour some light on this.
 
Warm Regards,
Dinakaran.
 
"Commonsence solve always better than technicality"

AnswerRe: Resume download from web client.memberxidar17 Jun '08 - 4:09 
BITS has authentication built in. So the user not only has to authenticate to the webpage containing the URL, but also within BITS to authenticate with the download. The credentials are then stored with the job (encrypted, of course) so the user can resume any time, fully authenticated, without having to go to your website again.
BITS will handle all those stuff for you, and SharpBITS adds as the .NET wrapper to this Smile | :)
 
Comments in my code? Why do you think do they call it 'code' ??

GeneralBITS Server configurationmemberVincent DUVERNET (Nolmë Informatique)20 May '08 - 12:40 
I've found this URL for BITS configuration :
 
http://technet2.microsoft.com/windowsserver/en/library/f7cae39f-9c94-4701-8dee-dd60a2bd96651033.mspx?mfr=true[^]
 
It works well on my 2003 Web Edition.
 
-------------------------
 
Just a comment, don't forget to call
manager.Jobs.Clear();
after
manager.EnumJobs(JobOwner.CurrentUser);
 
if you don't want all jobs to be chained after each debug Poke tongue | ;-P
Generalworking with bits over web application [modified]membercmartinez34521 Nov '07 - 11:51 
I have a question about bits 2.5 and It's Arquitecture. The Company
developed a web Application that centralizes all transfer form one site to
another (diferent IP's)
using the http protocol over a bandwith of 2 mb and works fine. I would
like to know if during the transfer, the information is retrieved from the
origin to
the central server (web application) and then sent to the destination, or if
Bits sends the información (makes some kind of reference) directly from the
origin to the destination. My guess is that Bits makes some kind of
reference.......
 
I would like to avoid a very slow functioning when 80 transfers arrive.
 
What is the best to do ......
 

-- modified at 12:07 Wednesday 28th November, 2007
QuestionRe: working with bits over web applicationmemberxidar3 Dec '07 - 13:02 
I don't really got your point, what information are you talking about?
 
Comments in my code? Why do you think do they call it 'code' ??

QuestionWrong LocalNamemembermsaponaro20 Sep '07 - 2:51 
Hi, I have a problem with the LocalName
I add a file to a job in this way
newJob.AddFile("http://localhost/bits/sole.doc", "C:\\Bits\\Client\\sole.doc");
The transfer is OK but the name of the file is something like BIT5CA.tmp
Can someone help me?
 
Thanks!!!!!


AnswerRe: Wrong LocalNamememberxidar20 Sep '07 - 4:10 
that's correct until you call Complete() on the Job after the transfer is finished (when JobState becomes "Transfered")
 
Comments in my code? Why do you think do they call it 'code' ??

GeneralError while adding files for concurrent download. [modified]memberSach7423 Nov '06 - 19:36 
Hi,
 
For single download its working but if change for concurrent download then throws error, could you please help me to find out where i am making mistake. that is coming at job1.AddFiles(BitsFileList);
 

BitsManager manager1 = new BitsManager();
manager1.EnumJobs(JobOwner.CurrentUser);
 
BitsJob job1 = manager1.CreateJob("Download Xml", JobType.Download);
 
System.Collections.ObjectModel.Collection<BitsFileInfo> BitsFileList = new System.Collections.ObjectModel.Collection<BitsFileInfo>();
 
//====this block is in loop to add multiple files=====
BitsFileInfo FileInfo = new BitsFileInfo(RemotePath, LocalPath);
BitsFileList.Add(FileInfo);
//======
 
job1.AddFiles(BitsFileList);
job1.EnumFiles();
job1.Resume();
 
One more issue to is there any call to activate concurrent download ?
 

GeneralRe: Error while adding files for concurrent download.memberxidar26 Nov '06 - 9:11 
Are you using the latest version of SharpBits available from the Homepage (http://sharpbits.xidar.net)? There was a bug using the AddFiles which is fixed already some time ago, but not posted to CP.
 
It's not possible to have concurrent downloads with BITS or either SharpBITS, this is by design.
 
Good code is like art - at least the author has to understand what it should express.

QuestionAny idea on how to implement this on web application?memberKhinLLK12 Nov '06 - 16:36 
Hi,
 
Nice work!
Do you have any idea on how to impelemnt the same behaviour on web applications?
I'm using VS.Net 2003 ( ASP.Net 1.1 )
I'm looking for the same feature for my web project.
Any suggestion is very much appreciated!
Thanks.
AnswerRe: Any idea on how to implement this on web application?memberxidar13 Nov '06 - 8:15 
what behaviour do you mean? BITS is a windows service and can be used on any windows machine (>=Win2k). So even a web application on ASP.NET 1.1 should be able to use.
Or please specify your requirements a bit more detailed, so we get a picture what you're trying to achieve.
 
Good code is like art - at least the author has to understand what it should express.

GeneralRe: Any idea on how to implement this on web application?memberKhinLLK13 Nov '06 - 14:40 
Actually, i'm trying to implement resume download/upload feature in web application.
Some of people suggest to use BITS.
So I was wondering is that possible to use in web application.
Thanks.
GeneralRe: Any idea on how to implement this on web application?memberxidar26 Nov '06 - 9:13 
if your WebApplication can access local Services than it should be possible to use BITS/SharpBits. Do we talk about server side or client?
QuestionRe: Any idea on how to implement this on web application?memberPadmaja B18 Sep '07 - 11:31 
Hi,
I would like to use SharpBits.Base_1.3 in asp.net application. When client browse web page, i would like to upload files present at client system to webserver using BITS.
Can any one suggest me how can i do this?
 
Thanks
Padmaja
AnswerRe: Any idea on how to implement this on web application?memberxidar18 Sep '07 - 22:36 
you just need to implement a module which is able to access system components/services from the browser... as every malware tries to do Hmmm | :|
MS uses an ActiveX control for the WindowsUpdate functionality, which only runs in IE.
QuestionStable for file larger than 500MB?memberDave Lenz11 Oct '06 - 20:43 
Have you done any test on file larger than 500 MB?
 
Microsoft SUS uses this technology?
 
Thank you!
AnswerRe: Stable for file larger than 500MB?memberxidar12 Oct '06 - 3:01 
no dedicated tests, just using it. Downloads as well as Uploads. One of the reasons I started using BITS was the challenge to upload large files (>1GB) over slow internet connections, where it usually takes days or weeks to finish. No problems so far, very reliable, and as long as the BITS system service itself is running, you don't have to take care to restart anything if you reboot machine or connection was broken.
If SUS is the Windows Update Service (?), than it uses BITS. With the small UI application I developed, you can watch the download progress of Windows Update as well Wink | ;)
GeneralNice onememberBo B18 Jul '06 - 22:09 
I think I might be able to use this for a crawler type job I have to code. So thanks for posting this!
GeneralUImemberDomenic11 Jul '06 - 3:56 
Where's the nifty UI that you have a screenshot of. I like it! Your download files only have the console version.
GeneralRe: UImemberxidar11 Jul '06 - 18:47 
As stated above, this UI is not yet part of the contribution, since still in development. But you can install the most recent version from http://sharpbits.xidar.net, the code is public too.
GeneralRe: UImemberVincent DUVERNET (Nolmë Informatique)19 May '08 - 11:14 
HTTP 400 under IE7 (Vista SP1)
Bad Request (Invalid Hostname) under firefox 2.0.0.14 (Vista SP1)
 
Frown | :(
GeneralRe: UImemberxidar19 May '08 - 11:23 
sorry, our web server went down due to an hardware error. replacement has been shipped but not yet arrived, so it might take another day or two (everything has been redundant - except of the RAID-controller :/ )
 
Comments in my code? Why do you think do they call it 'code' ??

GeneralRe: UImemberNevering2 Nov '06 - 11:46 
I can't find the source for your UI ??
GeneralProxy and Server NTLM Authenticationmemberandrear10 Jul '06 - 0:31 
It seems missing the implementation of Proxy and Server SETCREDENTIALS, especially regarding NTLM schema, doesn't it?
Ant suggestion to integrate it?
 
aramacciotti@tiscali.it
GeneralRe: Proxy and Server NTLM Authenticationmemberxidar10 Jul '06 - 1:10 
BitsCredentials credentials = new BitsCredentials();
 
credentials.UserName = userName;
credentials.Password = password;
credentials.AuthenticationTarget = AuthenticationTarget.Server;
credentials.AuthenticationScheme = AuthenticationScheme.Ntlm;
 
job.AddCredentials(credentials);
 
You can also use AuthenticationTarget.Proxy for Proxy Authentication, and one of the various AuthenticationScheme values

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 7 Oct 2010
Article Copyright 2006 by xidar
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid