none
Get the network usage using GetLocalUsage or GetNetworkUsageAsync RRS feed

  • Question

  • When I am using GetLocalUsage method then after getting the data usage throwing exception:

    Unhandled Exception: System.Exception: Element not found. (Exception from HRESULT: 0x80070490)
       at Windows.Networking.Connectivity.ConnectionProfile.GetLocalUsage(DateTimeOffset StartTime, DateTimeOffset EndTime)
       at ConsoleApplication2.MainClass.GetNetworkUsage() in d:\userdata\ashfaque\documents\visual studio 2015\Projects\GetLength\GetLength\Program.cs:line 53

    If I use GetNetworkUsageAsync method then getting below error:

    Unhandled Exception: System.ArgumentException: Value does not fall within the expected range.
       at Windows.Foundation.IAsyncOperation`1.GetResults()
       at ConsoleApplication2.MainClass.GetNetworkUsage() in d:\userdata\ashfaqque\documents\visual studio 2015\Projects\GetLength\GetLength\Program.cs:line 60

    static void GetNetworkUsage()
            {
                IReadOnlyList<ConnectionProfile> connections = NetworkInformation.GetConnectionProfiles();
                ulong DataUsageWeek = 0;
                foreach (var connection in connections)
                {
                    if (connection == null) continue;
                    DataUsageWeek = connection.GetLocalUsage(DateTimeOffset.UtcNow - TimeSpan.FromDays(30), DateTimeOffset.UtcNow).BytesReceived +
                        connection.GetLocalUsage(DateTimeOffset.UtcNow - TimeSpan.FromDays(24), DateTimeOffset.UtcNow).BytesSent;
                    Console.WriteLine(DataUsageWeek / 1024);


                    //var networkUsages =  connection.GetNetworkUsageAsync(new DateTimeOffset(DateTime.Now.AddHours(24)), new DateTimeOffset(DateTime.Now), DataUsageGranularity.Total, new NetworkUsageStates()).GetResults();
                    //foreach (NetworkUsage uses in networkUsages)
                    //{
                    //    Console.WriteLine(uses.BytesReceived + uses.BytesSent);
                    //}               
                }}

     Please help me to get the data with any of the above methods.

    Thanks,

    Ashfaque Hussain

    Tuesday, November 13, 2018 12:29 PM

All replies

  • Hi,

    Well, there are some questions I want to ask.

    Is your app a UWP app? If so, what's the target version of your project? What's the OS version of your device?

    There are two things that you need to know. 

    First ConnectionProfile.GetLocalUsage Method is not recommend to used in UWP apps, it would be better to use ConnectionProfile.GetNetworkUsageAsync(DateTime, DateTime, DataUsageGranularity, NetworkUsageStates) Method.

    The second thing is that you are pass wrong parameters to ConnectionProfile.GetNetworkUsageAsync method and that is the reason for your error.

    You could see in the document that this method should be used as:

    GetNetworkUsageAsync(DateTimeOffset startTime, DateTimeOffset endTime, DataUsageGranularity granularity, NetworkUsageStates states)
    So in your code you are querying the network usage from future to now which is impossible.You need to adjust the position of the two parameters.


    Best regards,

    Roy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, November 14, 2018 8:04 AM
  • Thank you for your answer.

    I am using this API in my console application. I didn't get any API to get the data usage so trying to use these API.

    Yes you are correct, input to GetNetworkUsageAsync is wrong,

    Now I am using like that:

    var networkUsages =  connection.GetNetworkUsageAsync(new DateTimeOffset(DateTime.Now.AddDays(-30)), new DateTimeOffset(DateTime.Now), DataUsageGranularity.Total, new NetworkUsageStates()).GetResults();

    But still its throwing exception:

    An unhandled exception of type 'System.InvalidOperationException' occurred in GetUsageDemo.exe

    Additional information: A method was called at an unexpected time.

    Wednesday, November 14, 2018 9:08 AM
  • Hi Roy,

    I got some output, it may help you to identify the exception causes.

    In my system there are some wifi and LAN usage are there, above method is reading the data usage for all except one: you can get the output below:

    Connection Details:-
    Authentication Type:None
    Profile Name:Ethernet
    Data Usage:5188584
    ------------------------------------------------------------------------------
    Connection Details:-
    Authentication Type:Unknown
    Profile Name:Ash
    Data Usage:20239
    ------------------------------------------------------------------------------
    Connection Details:-
    Authentication Type:Unknown
    Profile Name:BLR
    Data Usage:9903
    ------------------------------------------------------------------------------
    Connection Details:-
    Authentication Type:Unknown
    Profile Name:FROZEN
    Data Usage:161552
    ------------------------------------------------------------------------------
    Connection Details:-
    Authentication Type:Rsna
    Profile Name:BLRSW

    Unhandled Exception: System.Exception: Element not found. (Exception from HRESULT: 0x80070490)
       at Windows.Networking.Connectivity.ConnectionProfile.GetLocalUsage(DateTimeOffset StartTime, DateTimeOffset EndTime)
       at ConsoleApplication2.MainClass.<GetNetworkUsage>d__0.MoveNext() in d:\userdata\ashfaque\documents\visual studio 2015\Projects\GetLength\GetLength\Program.cs:line 58
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__6_1(Object state)
       at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
       at System.Threading.ThreadPoolWorkQueue.Dispatch()
       at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
    Press any key to continue . . .

    Only when its trying to get usage from BLRSW then exception is throwing.

    Thanks

    Wednesday, November 14, 2018 12:45 PM
  • Hi,

    Is it a UWP console app or a desktop console app?

    From the error log I found that you are still using GetLocalUsage right? Please try to use the new API GetNetworkUsageAsync. It is a asynchronous method and you could use await/async instead of Getresult.

    Best regards,

    Roy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, November 15, 2018 10:15 AM
  • Hi Roy,

    Thank you for your response.

    Its desktop console app.

    Now I removed the GetLocalUsage and using the new API GetNetworkUsageAsync. Using async/await removed GetResult.

    But still throwing the same exception for me.

    Below is code snippet and results:

         static async void GetNetworkUsage()
         {
                IReadOnlyList<NetworkUsage> networkUsages = null;
                IReadOnlyList<ConnectionProfile> connections = NetworkInformation.GetConnectionProfiles();
                foreach (var connection in connections)
                {
                    if (connection == null) continue;
                    Console.WriteLine("Connection Details:-");
                    Console.WriteLine("Authentication Type:" + connection.NetworkSecuritySettings.NetworkAuthenticationType);

                    Console.WriteLine("Profile Name:" + connection.ProfileName);
                    networkUsages = await connection.GetNetworkUsageAsync(new DateTimeOffset(DateTime.Now.AddDays(-24)), new DateTimeOffset(DateTime.Now), DataUsageGranularity.Total, new NetworkUsageStates() { Shared = TriStates.DoNotCare });
                    foreach (NetworkUsage uses in networkUsages)
                    {
                        Console.WriteLine("Data Usage:" + uses.BytesReceived / 1024 + uses.BytesSent / 1024);
                        Console.WriteLine("------------------------------------------------------------------------------");
                    }
                }
            }

    Output:

    Connection Details:-
    Authentication Type:None
    Profile Name:Ethernet
    Data Usage:18337315743
    ------------------------------------------------------------------------------
    Connection Details:-
    Authentication Type:Unknown
    Profile Name:Ash
    Data Usage:116763191
    ------------------------------------------------------------------------------
    Connection Details:-
    Authentication Type:Unknown
    Profile Name:BLR
    Data Usage:8697772
    ------------------------------------------------------------------------------
    Connection Details:-
    Authentication Type:Unknown
    Profile Name:FROZEN
    Data Usage:14511011868
    ------------------------------------------------------------------------------
    Connection Details:-
    Authentication Type:Rsna
    Profile Name:BLRSW

    Unhandled Exception: System.Exception: Element not found. (Exception from HRESULT: 0x80070490)
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
       at ConsoleApplication2.MainClass.<GetNetworkUsage>d__0.MoveNext() in d:\userdata\ashfaque\documents\visual studio 2015\Projects\GetLength\GetLength\Program.cs:line 68
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__6_1(Object state)
       at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
       at System.Threading.ThreadPoolWorkQueue.Dispatch()
       at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
    Press any key to continue . . .

    Could you please look into that.

    Thursday, November 15, 2018 1:31 PM
  • Hi,

    I'll move this thread to Visual C# Forum, you could get more help there.

    Best regards,

    Roy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, November 16, 2018 3:17 AM
  • Hi Ashfaque Hussain,

    Could you please share a simple complete sample about the issue that could reproduce the issue on my side.

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, November 27, 2018 7:40 AM
    Moderator