Chilkat Examples

ChilkatHOMEAndroid™Classic ASPCC++C#Mono C#.NET Core C#C# UWP/WinRTDataFlexDelphi ActiveXDelphi DLLVisual FoxProJavaLianjaMFCObjective-CPerlPHP ActiveXPHP ExtensionPowerBuilderPowerShellPureBasicCkPythonChilkat2-PythonRubySQL ServerSwift 2Swift 3/4TclUnicode CUnicode C++Visual Basic 6.0VB.NETVB.NET UWP/WinRTVBScriptXojo PluginNode.jsExcelGo

VB.NET UWP/WinRT Web API Examples

Primary Categories

AWS Translate
Activix CRM
Adyen
Amazon MWS
Azure Maps
Azure Monitor
Azure OAuth2
Azure Storage Accounts
Bluzone
CardConnect
ClickBank
Clickatell
Cloudfare
DocuSign
ETrade
Facebook
GeoOp
GetHarvest
Jira

MYOB
Magento
Microsoft Calendar
Microsoft Group
Microsoft Tasks and Plans
OneLogin OIDC
PayPal
Peoplevox
Populi
QuickBooks
SOAP finkok.com
Shopify
Stripe
SugarCRM
Trello
Twitter
VoiceBase
Vonage
Walmart
Xero
eBay
effectconnect

 

 

 

(VB.NET UWP/WinRT) Facebook Download all Photos to Local Files

Demonstrates how to download all of one's Facebook photos to a local filesystem directory. This sample code keeps a local cache to avoid re-downloading the same photos twice. The program can be run again after a time, and it will download only photos that haven't yet been downloaded.

Chilkat Universal Windows Platform (UWP) / WinRT Downloads

Chilkat for the Universal Windows Platform (UWP)

' This example requires the Chilkat API to have been previously unlocked.
' See Global Unlock Sample for sample code.

' This example will use a local disk cache to avoid re-fetching the same
' photo id after it's been fetched once.
Dim fbCache As New Chilkat.Cache
' The cache will use 1 level of 256 sub-directories.
fbCache.Level = 1
' Use a directory path that makes sense on your operating system..
fbCache.AddRoot("C:/fbCache")

' This example assumes a previously obtained an access token
Dim oauth2 As New Chilkat.OAuth2
oauth2.AccessToken = "FACEBOOK-ACCESS-TOKEN"

Dim rest As New Chilkat.Rest

' Connect to Facebook.
Dim success As Boolean = Await rest.ConnectAsync("graph.facebook.com",443,True,True)
If (success <> True) Then
    Debug.WriteLine(rest.LastErrorText)
    Exit Sub
End If


' Provide the authentication credentials (i.e. the access key)
rest.SetAuthOAuth2(oauth2)

' There are two choices:  
' We can choose to download the photos the person is tagged in or has uploaded
' by setting type to "tagged" or "uploaded".
rest.AddQueryParam("type","uploaded")

' To download all photos, we begin with an outer loop that iterates over
' the list of photo nodes in pages.  Each page returned contains a list of 
' photo node ids.  Each photo node id must be retrieved to get the download URL(s)
' of the actual image.

' I don't know the max limit for the number of records that can be downloaded at once.
rest.AddQueryParam("limit","100")

' Get the 1st page of photos ids.
' See https://developers.facebook.com/docs/graph-api/reference/user/photos/ for more information.
Dim responseJson As String = Await rest.FullRequestNoBodyAsync("GET","/v2.7/me/photos")
If (rest.LastMethodSuccess <> True) Then
    Debug.WriteLine(rest.LastErrorText)
    Exit Sub
End If


Dim photoJson As New Chilkat.JsonObject
Dim saPhotoUrls As New Chilkat.StringArray
Dim sbPhotoIdPath As New Chilkat.StringBuilder

Dim json As New Chilkat.JsonObject
json.EmitCompact = False
json.Load(responseJson)

Dim i As Integer
Dim photoId As String
Dim imageUrl As String

' Get the "after" cursor.
Dim afterCursor As String = json.StringOf("paging.cursors.after")
While json.LastMethodSuccess = True

    Debug.WriteLine("-------------------")
    Debug.WriteLine("afterCursor = " & afterCursor)

    ' For each photo id in this page...
    i = 0
    Dim numItems As Integer = json.SizeOfArray("data")
    While i < numItems
        json.I = i
        photoId = json.StringOf("data[i].id")
        Debug.WriteLine("photoId = " & photoId)

        ' We need to fetch the JSON for this photo.  Check to see if it's in the local disk cache,
        ' and if not, then get it from Facebook.
        Dim photoJsonStr As String = fbCache.FetchText(photoId)
        If (fbCache.LastMethodSuccess = False) Then
            ' It's not locally available, so get it from Facebook..
            sbPhotoIdPath.Clear()
            sbPhotoIdPath.Append("/v2.7/")
            sbPhotoIdPath.Append(photoId)

            rest.ClearAllQueryParams()
            rest.AddQueryParam("fields","id,album,images")

            Debug.WriteLine("Fetching photo node from Facebook...")

            ' This REST request will continue using the existing connection.
            ' If the connection was closed, it will automatically reconnect to send the request.
            photoJsonStr = Await rest.FullRequestNoBodyAsync("GET",sbPhotoIdPath.GetAsString())
            If (rest.LastMethodSuccess <> True) Then
                Debug.WriteLine(rest.LastErrorText)
                Exit Sub
            End If

            ' Add the photo JSON to the local cache.
            fbCache.SaveTextNoExpire(photoId,"",photoJsonStr)
        End If


        ' Parse the photo JSON and add the main photo download URL to saPhotoUrls
        ' There may be multiple URLs in the images array, but the 1st one is the largest and main photo URL.
        ' The others are smaller sizes of the same photo.
        photoJson.Load(photoJsonStr)
        imageUrl = photoJson.StringOf("images[0].source")
        If (photoJson.LastMethodSuccess = True) Then

            ' Actually, we'll add a small JSON document that contains both the image ID and the URL.
            Dim imgUrlJson As New Chilkat.JsonObject
            imgUrlJson.AppendString("id",photoId)
            imgUrlJson.AppendString("url",imageUrl)
            saPhotoUrls.Append(imgUrlJson.Emit())
            Debug.WriteLine("imageUrl = " & imageUrl)
        End If


        i = i + 1
    End While

    ' Prepare for getting the next page of photos ids.
    ' We can continue using the same REST object.
    ' If already connected, we'll continue using the existing connection.
    ' Otherwise, a new connection will automatically be made if needed.
    rest.ClearAllQueryParams()
    rest.AddQueryParam("type","uploaded")
    rest.AddQueryParam("limit","20")
    rest.AddQueryParam("after",afterCursor)

    ' Get the next page of photo ids.
    responseJson = Await rest.FullRequestNoBodyAsync("GET","/v2.7/me/photos")
    If (rest.LastMethodSuccess <> True) Then
        Debug.WriteLine(rest.LastErrorText)
        Exit Sub
    End If


    json.Load(responseJson)
    afterCursor = json.StringOf("paging.cursors.after")
End While

Debug.WriteLine("No more pages of photos.")

' Now iterate over the photo URLs and download each to a file.
' We can use Chilkat HTTP.  No Facebook authorization (access token) is required to download
' the photo once the URL is known.  
Dim http As New Chilkat.Http

' We'll cache the image data so that if run again, we don't re-download the same image again.
Dim numUrls As Integer = saPhotoUrls.Count
i = 0
Dim urlJson As New Chilkat.JsonObject
Dim imageBytes() As Byte
Dim fac As New Chilkat.FileAccess

While i < numUrls
    urlJson.Load(saPhotoUrls.GetString(i))
    photoId = urlJson.StringOf("id")
    imageUrl = urlJson.StringOf("url")

    ' Check the local cache for the image data.
    ' Only download and save if not already cached.
    imageBytes = fbCache.FetchFromCache(imageUrl)
    If (fbCache.LastMethodSuccess = False) Then
        '  This photo needs to be downloaded.

        Dim sbImageUrl As New Chilkat.StringBuilder
        sbImageUrl.Append(imageUrl)

        ' Let's form a filename..
        Dim extension As String = ".jpg"
        If (sbImageUrl.Contains(".gif",False) = True) Then
            extension = ".gif"
        End If

        If (sbImageUrl.Contains(".png",False) = True) Then
            extension = ".png"
        End If

        If (sbImageUrl.Contains(".tiff",False) = True) Then
            extension = ".tiff"
        End If

        If (sbImageUrl.Contains(".bmp",False) = True) Then
            extension = ".bmp"
        End If


        Dim sbLocalFilePath As New Chilkat.StringBuilder
        sbLocalFilePath.Append("C:/Photos/facebook/uploaded/")
        sbLocalFilePath.Append(photoId)
        sbLocalFilePath.Append(extension)

        imageBytes = Await http.QuickGetAsync(imageUrl)
        If (http.LastMethodSuccess <> True) Then
            Debug.WriteLine(http.LastErrorText)
            Exit Sub
        End If


        ' We've downloaded the photo image bytes into memory.
        ' Save it to the cache AND save it to the output file.
        fbCache.SaveToCacheNoExpire(imageUrl,"",imageBytes)
        fac.WriteEntireFile(sbLocalFilePath.GetAsString(),imageBytes)

        Debug.WriteLine("Downloaded to " & sbLocalFilePath.GetAsString())
    End If


    i = i + 1
End While

Debug.WriteLine("Finished downloading all Facebook photos!")

 

© 2000-2019 Chilkat Software, Inc. All Rights Reserved.