# OpenAndSave

The following example demonstrates how to open a browser instance, save and restore a session, visit a webpage, perform actions (like login), and close the browser. The session is saved so that the next time the browser is opened, it restores the previous session without requiring you to log in again.

```csharp
static async Task Main(string[] args) {
    const string token = "YOUR CLOUDBROWSER.AI TOKEN";
    using BrowserService svc = new(token);

    // FIRST VISIT --------------------------------------------------------------------
    var browser = await OpenAndConnect(svc).ConfigureAwait(false);
    if (browser == null)
        return;

    var page = (await browser.PagesAsync().ConfigureAwait(false))[0];

    await page.GoToAsync("http://app.cloudbrowser.ai").ConfigureAwait(false);
    Console.WriteLine("Web visited");

    await Login(page).ConfigureAwait(false);
    await Task.Delay(5000).ConfigureAwait(false);

    await browser.CloseAsync().ConfigureAwait(false);
    Console.WriteLine("Browser closed");

    // SECOND VISIT -------------------------------------------------------------------
    await Task.Delay(1000).ConfigureAwait(false);

    browser = await OpenAndConnect(svc).ConfigureAwait(false);
    if (browser == null)
        return;

    page = (await browser.PagesAsync().ConfigureAwait(false))[0];

    await page.GoToAsync("http://app.cloudbrowser.ai").ConfigureAwait(false);
    Console.WriteLine("Web visited again");

    // This time, logging in is not necessary.
    await Task.Delay(5000).ConfigureAwait(false);

    await browser.CloseAsync().ConfigureAwait(false);
    Console.WriteLine("Browser closed");

    // CHECK STORED SESSIONS ----------------------------------------------------------
    using SessionService sessions = new(token);
    Console.WriteLine("Label | Created On | Last Update");
    var sessionRp = await sessions.List().ConfigureAwait(false);
    foreach(var s in sessionRp.Sessions) {
        Console.WriteLine("{0} | {1} | {2}",s.Label,s.CreatedOn, s.LastUpdate);
    }

    // REMOVE ONE SESSION
    await sessions.Remove("test").ConfigureAwait(false);
}

static async Task<IBrowser?> OpenAndConnect(BrowserService svc) {
    var rp = await svc.Open(new() {
        Label = "SessionSample",      // Label for the session
        SaveSession = true,           // Save session after browser closes
        RecoverSession = true        // Recover saved session on next browser launch
    }).ConfigureAwait(false);

    if (rp.Status == ResponseStatus.Succes) {
        Console.WriteLine("Browser requested");
    } else {
        Console.WriteLine("Error requesting browser: {0}", rp.Status.ToString());
        return null;
    }

    return await Puppeteer.ConnectAsync(new ConnectOptions {
        BrowserWSEndpoint = rp.Address,
        DefaultViewport = null,
        AcceptInsecureCerts = true,
        SlowMo = 0
    }).ConfigureAwait(continueOnCapturedContext: false);
}

static async Task Login(IPage page) {
    // Simulating login by filling out email and password fields and submitting the form
    await page.TypeAsync("[type=\"email\"]", "email").ConfigureAwait(false);
    await page.TypeAsync("[type=\"password\"]", "password").ConfigureAwait(false);
    await page.ClickAsync("[type=\"submit\"]").ConfigureAwait(false);
}
```

***

#### F**ull example**

{% embed url="<https://github.com/CloudBrowser-AI/CloudBrowserAiSharp/blob/main/samples/OpenAndSave.cs/Program.cs>" %}

#### **How It Works**

1. **Initialize the Client**:\
   Create an instance of `BrowserService` using your API token.
2. **Request a Browser Instance with Session Saving and Recovery**:\
   Call `svc.Open()` with the following options:
   * **Label**: Set a custom label for the browser session.
   * **SaveSession**: Enable session saving, so that the state of the session (like cookies and local storage) is stored.
   * **RecoverSession**: Enable session recovery, so the session is restored the next time the browser is opened.
3. **Perform Actions**:\
   Navigate to a webpage (in this case, `http://app.cloudbrowser.ai`), simulate a login, and close the browser.
4. **Session Restore**:\
   On the second visit, the session is automatically restored, so you don’t need to log in again.
5. **Manage Stored Sessions**:\
   Use the `SessionService` to list all stored sessions, remove a session, or interact with them as needed.
6. **Close the Browser**:\
   The browser can be closed after each interaction using `browser.CloseAsync()`. The session data is saved for the next time you open the browser with session recovery enabled.

***

This approach enables you to save and restore sessions across multiple visits to the same page, making it more efficient for use cases like logging in once and maintaining the session for subsequent visits.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cloudbrowser.gitbook.io/docs/libraries/.net-client/openandsave.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
