1

I am using AzureAd along with the Microsoft Graph Client to do calculations on Excel spreadsheets. It works most of the time but every now and again the request comes back with a Invalid Session error:

Status Code: BadRequest
Microsoft.Graph.ServiceException: Code: InvalidSession
Message: The target session is invalid.
Inner error:
    Code: invalidSessionReCreatable
Message: The session specified in the request does not exist or is invalid due to a transient error.
Inner error:
    Code: InvalidOrTimedOutSession
Message: We noticed that you haven't been interacting with this workbook, so we paused your session.

It seems like the session gets paused before the API gets to finish the call (which happens in less than a second).

Startup Code to configure AD and Graph Services:

    services.AddMicrosoftIdentityWebApiAuthentication(Configuration, "AzureAd")
    .EnableTokenAcquisitionToCallDownstreamApi()
    .AddMicrosoftGraph(Configuration.GetSection("GraphBeta"))
    .AddInMemoryTokenCaches();

Creating the session:

        WorkbookSessionInfo res = await _graphServiceClient.Groups[_groupId].Drive.Items[productStructureCalculator.CalculatorId].Workbook
            .CreateSession(persistChanges)
            .Request()
            .Header("Prefer", "respond-async")
            .PostAsync();

Doing a batch request:

    var batchRequestInfo = CreateBatchRequestAsync(sessionId, structure, productStructureCalculator, productMatrixInputs);

    var resultRequest = _graphServiceClient.Groups[_groupId].Drive.Items[productStructureCalculator.CalculatorId].Workbook.Worksheets[productStructureCalculator.SheetName]
            .Range("D6:J6")
            .Request()
            .Header("workbook-session-id", "{" + sessionId + "}")
            .Header("Prefer", "return=minimal")
            .GetHttpRequestMessage();
    resultRequest.Method = HttpMethod.Get;

    var resultRequestID = Guid.NewGuid().ToString();
    var batchResultRequestStep = new BatchRequestStep(
        resultRequestID,
        resultRequest,
        new List<string> { batchRequestInfo.LastEventRequestId }
    );

    batchRequestInfo.BatchRequestContent.AddBatchRequestStep(batchResultRequestStep);

    var returnedResponse = await _graphServiceClient.Batch.Request().PostAsync(batchRequestInfo.BatchRequestContent);

1 Answers1

1

As per | Microsoft Docs ,

InvalidSessionReCreatable :The session specified in the request does not exist or is invalid due to a transient error.

Error Handling : The Microsoft Graph client can try to recreate a session and resume the work. Further access to the session specified in the failed request is not expected.

Please Check if the below work arounds help in your case:

1) use the CreateSession method > workbook: createSession | Microsoft Docs to get the workbook info, and set the persistChanges setting. =>(Set var persistChanges = true; )

Code:

var persistChanges = true;

    try
    {

 WorkbookSessionInfo res = await _graphServiceClient.Groups[_groupId].Drive.Items[productStructureCalculator.CalculatorId].Workbook
        .CreateSession(persistChanges)
        .Request()
        .Header("Prefer", "respond-async")
        .PostAsync();


        var result = res;

        return result;
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error getting items: {ex.Message}");
        return null;
}

Reference-SO

Or

2) You can set the Timeout to a higher value .Lets say one hour:

graphServiceClient.HttpProvider.OverallTimeout = TimeSpan.FromHours(1);

Or

3) Add session in start up class Ex:

services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromMinutes(30);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;

At least chance, take a look at activityBasedTimeoutPolicy which Represents a policy that can control the idle timeout for web sessions for applications that support activity-based timeout functionality.

kavyaS
  • 8,026
  • 1
  • 7
  • 19
  • Hi kavyasaraboju-MT, thank you so much for your answer. I can unfortunately not persist the changes as the excel workbooks are used as calculators and changes to the spreadsheet might cause issues. I did however give #2 a go and extended the timeout. I am afraid that the issue might not be with the graph client timing out but rather the connection between the graph client and the Excel backend (if that makes any sense). It is quite difficult to say if it works or not because it only happens occasionally, but I will give an update within a week. Thank you! – Wynand Coetzer Aug 17 '21 at 08:07
  • Unfortunately after a week of running perfectly the Graph calls started failing again with the inner error message of : "We noticed that you haven't been interacting with this workbook, so we paused your session.". I tried everything you mentioned with no success. There are also no activityBasedTimeoutPolicies set. It is a weird issue because the session is created before each calculation and literally times out within milliseconds. I was thinking that it might be a limit per week as it always breaks on a Monday or Tuesday. – Wynand Coetzer Aug 23 '21 at 12:55