OneDrive Class
Properties Methods Events Configuration Settings Errors
The OneDrive component provide an easy way to upload, download, and manage files and folders with Microsoft OneDrive.
Class Name
InCloudStorage_OneDrive
Procedural Interface
incloudstorage_onedrive_open(); incloudstorage_onedrive_close($res); incloudstorage_onedrive_register_callback($res, $id, $function); incloudstorage_onedrive_get_last_error($res); incloudstorage_onedrive_get_last_error_code($res); incloudstorage_onedrive_set($res, $id, $index, $value); incloudstorage_onedrive_get($res, $id, $index); incloudstorage_onedrive_do_abortupload($res); incloudstorage_onedrive_do_addqueryparam($res, $name, $value); incloudstorage_onedrive_do_config($res, $configurationstring); incloudstorage_onedrive_do_copyresource($res, $folderid, $newresourcename); incloudstorage_onedrive_do_createfolder($res, $foldername); incloudstorage_onedrive_do_createlink($res, $readonly); incloudstorage_onedrive_do_deleteresource($res); incloudstorage_onedrive_do_downloadfile($res); incloudstorage_onedrive_do_getcopyinfo($res); incloudstorage_onedrive_do_getdriveinfo($res); incloudstorage_onedrive_do_getresourceinfo($res); incloudstorage_onedrive_do_getuploadstatus($res); incloudstorage_onedrive_do_interrupt($res); incloudstorage_onedrive_do_listchanges($res); incloudstorage_onedrive_do_listdrives($res); incloudstorage_onedrive_do_listresources($res); incloudstorage_onedrive_do_moveresource($res, $folderid); incloudstorage_onedrive_do_search($res, $query); incloudstorage_onedrive_do_updateresource($res); incloudstorage_onedrive_do_uploadfile($res, $filetitle);
Remarks
The OneDrive class provides a simple interface to working with Microsoft OneDrive. Capabilities include uploading and downloading files, strong encryption support, creating folders, moving and copying resource, and more.
To begin, first create an account and register your application with OneDrive. Consult the OneDrive documentation for instructions on this process.
Authentication
Authentication is performed via OAuth 2.0. Use the OAuth class included in the toolkit, or any other OAuth
implementation to perform authentication and retrieve an authorization string. Once you've obtained an
authorization string like:
Bearer ya29.AHES6ZSZEJzATdZYjeihDn5W-VrXSsxEZu5p0pclxGdKKQAssign this value to the Authorization property before attempting any operations. Consult the OneDrive documentation for this particular service for more information about supported scope values and more details on OAuth authentication.
Listing Resources
ListResources lists resources within the drive at the specified path.
Calling this method without specifying ResourceParentId or ResourceParentPath will list all resources in the drive's root. To list resources of a specific folder set either ResourceParentId or ResourceParentPath prior to calling this method. When ResourceParentId is set, it takes precedence over ResourceParentPath.
When either ResourceParentId or ResourceParentPath, children of the specified parent folder will be listed. These two properties can be set before calling this method to navigate the drive. If both are specified ResourceParentId takes precedence. If both are unspecified the drive root is assumed.
After calling this method set ResourceIndex to a value from 0 to ResourceCount - 1. Setting ResourceIndex populates other Resource properties to provide information about the resource. After calling this method the following resource properties are populated:
- ResourceCount
- ResourceCRC32Hash
- ResourceCreatedDate
- ResourceData
- ResourceDeleted
- ResourceDescription
- ResourceDownloadURL
- ResourceETag
- ResourceId
- ResourceIndex
- ResourceMarker
- ResourceMIMEType
- ResourceModifiedDate
- ResourceName
- ResourceParentId
- ResourceParentPath
- ResourcePath
- ResourceSHA1Hash
- ResourceSize
- ResourceType
- ResourceWebURL
If the results are paged ResourceMarker will be populated. Call ListResources again to retrieve the next page of results. Continue calling ListResources until ResourceMarker is empty string to retrieve all pages.
onedrive.ListResources(); for (int i = 0; i < onedrive.ResourceCount; i++) { onedrive.ResourceIndex = i; Console.WriteLine(onedrive.ResourceName); Console.WriteLine(onedrive.ResourceSize); Console.WriteLine(onedrive.ResourceModifiedDate); }
Downloading Files
The DownloadFile method downloads a specific file.
Any of the following properties may be set to specify the file to download:
If LocalFile is set the file will be saved to the specified location. If LocalFile is not set the file data will be held by ResourceData.To decrypt an encrypted file set EncryptionAlgorithm and EncryptionPassword before calling this method.
onedrive.ResourceId = fileId; onedrive.LocalFile = "../MyFile.zip"; onedrive.DownloadFile();
Resuming Downloads
The class also supports resuming failed downloads by using the StartByte property. If the download was interrupted, set StartByte to the appropriate offset before calling this method to resume the download.
onedrive.ResourceId = fileId; onedrive.LocalFile = downloadFile; onedrive.DownloadFile(); //The transfer is interrupted and DownloadFile() above fails. Later, resume the download: //Get the size of the partially download file onedrive.StartByte = new FileInfo(downloadFile).Length; onedrive.ResourceId = fileId; onedrive.LocalFile = downloadFile; onedrive.DownloadFile();
Resuming Encrypted File Downloads
Resuming encrypted file downloads is only supported when LocalFile was set in the initial download attempt. When beginning an encrypted download if LocalFile is set the class will create a temporary file in TempPath to hold the encrypted data until it is complete.
If the download is interrupted DownloadTempFile will be populated with the temporary file holding the partial data.
When resuming, DownloadTempFile must be populated along with StartByte to allow the remainder of the encrypted data
to be downloaded. Once the encrypted data is downloaded it will be decrypted and written to LocalFile.
onedrive.ResourceId = fileId; onedrive.LocalFile = downloadFile; onedrive.EncryptionPassword = "password"; onedrive.DownloadFile(); //The transfer is interrupted and DownloadFile() above fails. Later, resume the download: //Get the size of the partially download temp file onedrive.StartByte = new FileInfo(onedrive.Config("DownloadTempFile")).Length; onedrive.ResourceId = fileId; onedrive.LocalFile = downloadFile; onedrive.EncryptionPassword = "password"; onedrive.DownloadFile();
Uploading Files
LocalFile specifies the file to upload. The data to upload may also be set in ResourceData .
The FileTitle parameter of UploadFile specifies the name of the file to be written in the drive.
To upload a file in a specific folder set ResourceParentId or ResourceParentPath to indicate the parent folder. If both are specified ResourceParentId takes precedence. If both are unspecified the drive root is assumed.
To encrypt a file before uploading set EncryptionAlgorithm and EncryptionPassword.
The UploadFile method returns the Id of the resource which was uploaded.
Upload Notes
Microsoft OneDrive offers two ways to upload a file. For smaller files a simple upload option is provided to upload data in one request. This is the default option. For larger files uploads can be fragmented into multiple pieces, allowing resuming of uploads that may be interrupted.
Simple
By default the class uses the simple upload mechanism. Only files up to 100 MB can be uploaded using the default simple upload.
onedrive.LocalFile = "../MyFile.zip"; onedrive.UploadFile("MyFile.zip");
The following properties are applicable when calling UploadFile and UseResumableUpload if False (default - simple upload):
Resumable
To enable resumable uploads set UseResumableUpload to True. This is recommended for files larger than 10 MB. The class will automatically fragment the specified file into smaller pieces and upload each individually. FragmentSize may be set to specify the size of the fragment if desired. The default fragment size is 10 MB.
When UseResumableUpload is set to True and UploadFile is called a resumable upload session is started by the class. ResumeURL is populated with the URL identifying the session. This value may be needed for additional operations if the upload does not complete normally. Additionally StartByte is updated as necessary by the class to indicate the current offset in the file.
If the upload is interrupted for any reason the upload may be resumed. To resume an upload verify that ResumeURL and StartByte are populated. If the same instance of the class is used these should already be populated and no special action is needed. Call UploadFile again to resume the upload at the specified StartByte offset.
If a resumable upload is interrupted for any reason, AbortUpload may be called to cancel the upload. If the upload is not resumed after some time the upload session will expire. UploadExpDate may be checked to determine when the upload session expires.
GetUploadStatus may be used to check the status of a resumable upload. The FragmentComplete event fires after each fragment is uploaded to indicate overall progress.
onedrive.LocalFile = "../MyFile.zip"; onedrive.UploadFile("MyFile.zip"); //The transfer is interrupted and UploadFile() above fails. Later, resume the download. //Using the same instance StartByte and ResumeURL are already populated //from the previous upload attempt onedrive.UploadFile("MyFile.zip");
The following properties are applicable when calling UploadFile and UseResumableUpload if True:
Additional Functionality
The OneDrive component offers advanced functionality beyond simple uploads and downloads. For instance:
- Encrypt and decrypt files using EncryptionAlgorithm and EncryptionPassword.
- Use CopyResource, MoveResource, DeleteResource, and UpdateResource to manage files and folders.
- CreateLink creates shareable links to content.
- ListChanges lists all changes in a drive from a given point to facilitate syncing local and remote copies.
- Search can be used to search for matching content.
- ListDrives provides the capability for multiple drives.
- And more!
Property List
The following is the full list of the properties of the class with short descriptions. Click on the links for further details.
Authorization | OAuth 2.0 Authorization Token. |
CopyPercentDone | The progress of the copy operation. |
CopyStatus | The status of the copy operation. |
DriveCount | The number of drives available to the user. |
DriveDeletedSpace | The space consumed by deleted files in bytes. |
DriveId | The unique id of the selected drive. |
DriveIndex | Selects a drive. |
DriveOwnerId | The Id of the drive owner. |
DriveOwnerName | The name of the drive owner. |
DriveRemainingSpace | The remaining unused space in bytes. |
DriveState | The state of the drive space. |
DriveTotalSpace | The total space of the drive in bytes. |
DriveType | The type of drive. |
DriveUsedSpace | The used space in bytes. |
EncryptionAlgorithm | The encryption algorithm. |
EncryptionPassword | The encryption password. |
FirewallAutoDetect | This property tells the component whether or not to automatically detect and use firewall system settings, if available. |
FirewallType | This property determines the type of firewall to connect through. |
FirewallHost | This property contains the name or IP address of firewall (optional). |
FirewallPassword | This property contains a password if authentication is to be used when connecting through the firewall. |
FirewallPort | This property contains the TCP port for the firewall Host . |
FirewallUser | This property contains a user name if authentication is to be used connecting through a firewall. |
LocalFile | The location of the local file. |
LocalHost | The name of the local host or user-assigned IP interface through which connections are initiated or accepted. |
Overwrite | Whether to overwrite the local or remote file. |
ProxyAuthScheme | This property is used to tell the component which type of authorization to perform when connecting to the proxy. |
ProxyAutoDetect | This property tells the component whether or not to automatically detect and use proxy system settings, if available. |
ProxyPassword | This property contains a password if authentication is to be used for the proxy. |
ProxyPort | This property contains the TCP port for the proxy Server (default 80). |
ProxyServer | If a proxy Server is given, then the HTTP request is sent to the proxy instead of the server otherwise specified. |
ProxySSL | This property determines when to use SSL for the connection to the proxy. |
ProxyUser | This property contains a user name, if authentication is to be used for the proxy. |
QueryParamsCount | The number of records in the QueryParams arrays. |
QueryParamsName | This property contains the name of the parameter to be used in a Query request. |
QueryParamsValue | This property contains the value of the parameter to be used in a Query request. |
ResourceChildren | The number of immediate children in the selected folder. |
ResourceCount | The number of files and folders. |
ResourceCRC32Hash | The CRC32 hash value. |
ResourceCreatedDate | The date when the item was created. |
ResourceData | Holds the file data after downloading or sets the file data before uploading or updating. |
ResourceDeleted | Whether the resource is deleted. |
ResourceDescription | A short description of the file or folder. |
ResourceDownloadURL | The URL used to download the file contents. |
ResourceETag | The ETag of the resource. |
ResourceId | The unique identifier of the resource. |
ResourceIndex | Selects the file or folder. |
ResourceMarker | The marker specifying the next set of results. |
ResourceMIMEType | The MIME type of the file. |
ResourceModifiedDate | The date when the item was modified. |
ResourceName | The name of the resource. |
ResourceParentId | The Id of the parent resource. |
ResourceParentPath | The path of the parent resource. |
ResourcePath | The full path to the specified resource. |
ResourceSHA1Hash | The SHA-1 hash value. |
ResourceSize | The size of the resource in bytes. |
ResourceType | Indicates whether the current entry is a folder or a file. |
ResourceWebURL | The URL to view the resource in a browser. |
ResumeURL | The URL for the resumable upload. |
SSLAcceptServerCertEncoded | The certificate (PEM/base64 encoded). |
SSLCertEncoded | The certificate (PEM/base64 encoded). |
SSLCertStore | The name of the certificate store for the client certificate. |
SSLCertStorePassword | If the certificate store is of a type that requires a password, this property is used to specify that password in order to open the certificate store. |
SSLCertStoreType | The type of certificate store for this certificate. |
SSLCertSubject | The subject of the certificate used for client authentication. |
SSLServerCertEncoded | The certificate (PEM/base64 encoded). |
StartByte | The byte offset from which to start the upload or download. |
Timeout | A timeout for the component. |
URL | The server URL. |
UseResumableUpload | Whether to use resumable uploads. |
Method List
The following is the full list of the methods of the class with short descriptions. Click on the links for further details.
AbortUpload | Aborts the resumable upload session. |
AddQueryParam | Adds a query parameter to the QueryParams properties. |
Config | Sets or retrieves a configuration setting . |
CopyResource | Copies the specified resource. |
CreateFolder | Creates a new folder. |
CreateLink | Creates a link for sharing the resource. |
DeleteResource | Deletes the specified resource. |
DownloadFile | Downloads the specified file. |
GetCopyInfo | Gets information about the copy operation. |
GetDriveInfo | Gets information about the drive. |
GetResourceInfo | Gets information about the resource. |
GetUploadStatus | Get the status of a resumable upload session. |
Interrupt | Interrupt the current method. |
ListChanges | Lists changes to the drive. |
ListDrives | List drives available to the user. |
ListResources | List resources in the current folder. |
MoveResource | Moves the specified resource to a new folder. |
Search | This method searches for resources matching the specified query. |
UpdateResource | Updates the resource. |
UploadFile | Uploads a file. |
Event List
The following is the full list of the events fired by the class with short descriptions. Click on the links for further details.
DriveList | Fired for each drive when ListDrives is called. |
EndTransfer | Fired when a document finishes transferring. |
Error | Information about errors during data delivery. |
FragmentComplete | This event fires after each fragment of a resumable upload is completed. |
ResourceList | Fired for each resource listed. |
SSLServerAuthentication | Fired after the server presents its certificate to the client. |
SSLStatus | Shows the progress of the secure connection. |
StartTransfer | Fired when a document starts transferring (after the headers). |
Transfer | Fired while a document transfers (delivers document). |
Configuration Settings
The following is a list of configuration settings for the class with short descriptions. Click on the links for further details.
CopyStatusURL | The URL from which copy status info is obtained. |
DownloadTempFile | The temporary file used when downloading encrypted data. |
FragmentSize | The fragment size. |
MaxResults | The maximum number of results to return when calling ListResources. |
RenameIfExists | Whether to rename the uploaded file if it exists. |
TempPath | The path to the directory where temporary files are created. |
UploadExpDate | The expiration of the resumable upload session. |
EncryptionIV | The initialization vector to be used for encryption/decryption. |
EncryptionKey | The key to use during encryption/decryption. |
XPath | Provides a way to point to a specific element in the returned XML response. |
XElement | The name of the current element. |
XParent | The parent of the current element. |
XSubTree | A snapshot of the current element in the document. |
XText | The text of the current element. |
XChildCount | The number of child elements of the current element. |
XChildName[x] | The name of the child element. |
XChildXText[x] | The inner text of the child element. |
AcceptEncoding | Used to tell the server which types of content encodings the client supports. |
AllowHTTPCompression | This property enables HTTP compression for receiving data. |
AllowIdenticalRedirectURL | Allow redirects to the same URL. |
Append | Whether to append data to LocalFile. |
Authorization | The Authorization string to be sent to the server. |
BytesTransferred | Contains the number of bytes transferred in the response data. |
EncodeURL | If set to true the URL will be encoded by the component. |
FollowRedirects | Determines what happens when the server issues a redirect. |
GetOn302Redirect | If set to true the component will perform a GET on the new location. |
HTTPVersion | The version of HTTP used by the component. |
IfModifiedSince | A date determining the maximum age of the desired document. |
KeepAlive | Determines whether the HTTP connection is closed after completion of the request. |
MaxRedirectAttempts | Limits the number of redirects that are followed in a request. |
OtherHeaders | Other headers as determined by the user (optional). |
ProxyAuthorization | The authorization string to be sent to the proxy server. |
ProxyAuthScheme | The authorization scheme to be used for the proxy. |
ProxyPassword | A password if authentication is to be used for the proxy. |
ProxyPort | Port for the proxy server (default 80). |
ProxyServer | Name or IP address of a proxy server (optional). |
ProxyUser | A user name if authentication is to be used for the proxy. |
TransferredDataLimit | The maximum number of incoming bytes to be stored by the component. |
TransferredHeaders | The full set of headers as received from the server. |
UseChunkedEncoding | Enables or Disables HTTP chunked encoding for transfers. |
ChunkSize | Specifies the chunk size in bytes when using chunked encoding. |
UserAgent | Information about the user agent (browser). |
KerberosSPN | The Service Principal Name for the Kerberos Domain Controller. |
ConnectionTimeout | Sets a separate timeout value for establishing a connection. |
FirewallAutoDetect | Tells the component whether or not to automatically detect and use firewall system settings, if available. |
FirewallHost | Name or IP address of firewall (optional). |
FirewallPassword | Password to be used if authentication is to be used when connecting through the firewall. |
FirewallPort | The TCP port for the FirewallHost;. |
FirewallType | Determines the type of firewall to connect through. |
FirewallUser | A user name if authentication is to be used connecting through a firewall. |
KeepAliveTime | The inactivity time in milliseconds before a TCP keep-alive packet is sent. |
KeepAliveInterval | The retry interval, in milliseconds, to be used when a TCP keep-alive packet is sent and no response is received. |
Linger | When set to True, connections are terminated gracefully. |
LingerTime | Time in seconds to have the connection linger. |
LocalHost | The name of the local host through which connections are initiated or accepted. |
LocalPort | The TCP port in the local host where the component binds. |
MaxLineLength | The maximum amount of data to accumulate when no EOL is found. |
MaxTransferRate | The transfer rate limit in bytes per second. |
RecordLength | The length of received data records. |
TCPKeepAlive | Determines whether or not the keep alive socket option is enabled. |
UseIPv6 | Whether to use IPv6. |
TcpNoDelay | Whether or not to delay when sending packets. |
ReuseSSLSession | Determines if the SSL session is reused. |
SSLCipherStrength | The minimum cipher strength used for bulk encryption. |
SSLEnabledProtocols | Used to enable/disable the supported security protocols. |
SSLProvider | The name of the security provider to use. |
SSLSecurityFlags | Flags that control certificate verification. |
OpenSSLCADir | The path to a directory containing CA certificates. |
OpenSSLCAFile | Name of the file containing the list of CA's trusted by your application. |
OpenSSLCipherList | A string that controls the ciphers to be used by SSL. |
OpenSSLPrngSeedData | The data to seed the pseudo random number generator (PRNG). |
AbsoluteTimeout | Determines whether timeouts are inactivity timeouts or absolute timeouts. |
FirewallData | Used to send extra data to the firewall. |
InBufferSize | The size in bytes of the incoming queue of the socket. |
OutBufferSize | The size in bytes of the outgoing queue of the socket. |
CodePage | The system code page used for Unicode to Multibyte translations. |