0
votes

I am currently working on Windows 10 Background Tasks and I am storing user location in my database and using time trigger, I am trying to send the stored data to the server using REST Webservice and I am using RestSharp.Portable API to do that. Now, the issue with is that, the request is not sent to the server when I call the web service from Background tasks but when I do same in the foreground (in my Windows 10 Project) then it works fine. Can someone suggest what I am doing wrong?

**My TimeTrigger Task

namespace TimerTask
{
public sealed class TimeTriggerTask : IBackgroundTask
{
    private ApplicationDataContainer userSettings = ApplicationData.Current.LocalSettings;

    public async void Run(IBackgroundTaskInstance taskInstance)
    {
        DatabaseManager dbManager = new DatabaseManager();
        var location_records = dbManager.getLocationDetails();
        if (MCSManager.Instance.currentClientData == null)
        {
            ResourceContext resourceContext = ResourceContext.GetForViewIndependentUse();
            ResourceMap resourceMap = MCSExtensions.getResourceMap();
            MCSManager.Instance.currentClientData = await new JsonDataHandler().LoadJsonFileforBackgroundTask(resourceMap.GetValue("CLIENT_JSON_FILENAME",resourceContext).ValueAsString, typeof(ClientData)) as ClientData;
        }
        if (location_records !=null && location_records.Count>0)
        {
            Dictionary<string, object> contentDictionary = new Dictionary<string, object>();
            contentDictionary.Add("P_LOC_DATA", location_records);
            contentDictionary.Add("P_LAST_LOC_LAT",location_records[location_records.Count-1].LATITUDE);
            contentDictionary.Add("P_LAST_LOC_LNG", location_records[location_records.Count - 1].LONGITUDE);
            contentDictionary.Add("P_LAST_LOC_UPDATE", location_records[location_records.Count - 1].DATE_TIME);
            IRestResponse locationTrackingResponse = await new WebServiceUtility().CommonWebservice(new RequestDataGenerator().generateRequestDataForLocationTracking(contentDictionary));

            if (locationTrackingResponse.IsSuccess==true && locationTrackingResponse.RawBytes.Length>0)
            {
                byte[] decryptedbytes = WebserviceED.finaldecryptedresponse(locationTrackingResponse.RawBytes);
                string responsejson = Encoding.UTF8.GetString(decryptedbytes, 0, decryptedbytes.Length);
                JObject userInfo = JObject.Parse(responsejson);
                string result = (string)userInfo["P_RESULT"];
                if(result !=null && result.Equals("1"))
                {
                    dbManager.TruncateAllLocationTrackingData();
                    Debug.WriteLine("Data deleted successfully");
                }

            }
        }

        // simple example with a Toast, to enable this go to manifest file
        // and mark App as TastCapable - it won't work without this
        // The Task will start but there will be no Toast.
        /*ToastTemplateType toastTemplate = ToastTemplateType.ToastText02;
        XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
        XmlNodeList textElements = toastXml.GetElementsByTagName("text");
        textElements[0].AppendChild(toastXml.CreateTextNode("My first Task - Yeah"));
        textElements[1].AppendChild(toastXml.CreateTextNode("I'm a message from your background task!"));
        ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml));*/
    }
}

}

My Webservice call public async Task CommonWebservice(string encryptedstring) { ResourceContext resourceContext = ResourceContext.GetForViewIndependentUse(); ResourceMap resourceMap = MCSExtensions.getResourceMap();

        var client = new RestClient(BaseUrl + resourceMap.GetValue("WEB_SERVICE_NAME",resourceContext).ValueAsString);

        RestRequest request = new RestRequest(HttpMethod.Post);

        byte[] encryptedbytes = System.Text.Encoding.UTF8.GetBytes(encryptedstring);
        request.AddParameter("", encryptedbytes, ParameterType.RequestBody);

        var response = await client.Execute(request);

        return response;
    }

I have already registered the Background task in my application. Also, I got a suggestion to add Deferral when we use async and await.

1
please post your full source code of the background task. also make sure you registed the task when app launchthang2410199
@thang2410199 added my background task code and I have registered it. Please also suggest where I should add deferral in my background task.Kinjan Bhavsar

1 Answers

2
votes

The request is not executed properly, the background task is killed before the request is handled.

add the following code to the beginning of your task

//get deferral to make the call awaitable BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();

and the following code to the end

//Complete the task _deferral.Complete();

You can always debug your background task to make sure it work ok.