Example #1
0
        public async Task <(bool, string, List <AirtableRecord>)> FetchRecordsFilterByFormula(string table, string formula, List <string> fields)
        {
            string errorMessage = null;
            bool   success      = false;

            var    records = new List <AirtableRecord>();
            string offset  = null;

            using (AirtableBase airtableBase = new AirtableBase(ApiKey, BaseId)) {
                Task <AirtableListRecordsResponse> task = airtableBase.ListRecords(
                    table, offset, fields, formula);

                AirtableListRecordsResponse response = await task;

                if (response.Success)
                {
                    records.AddRange(response.Records.OrderBy(r => r.Fields["Date"]).ToList());
                    offset = response.Offset;
                }
                else if (response.AirtableApiError is AirtableApiException)
                {
                    errorMessage = response.AirtableApiError.GetBaseException().Message;
                }
                else
                {
                    errorMessage = "Unknown error";
                }
                success = response.Success;
            }
            return(success, errorMessage, records);
        }
Example #2
0
        public async Task <int> GetCount()
        {
            int count = 0;

            using (AirtableBase airtableBase = new AirtableBase(_appKey, _baseId))
            {
                Task <AirtableListRecordsResponse <ViewersTable> > task = airtableBase.ListRecords <ViewersTable>(
                    "Viewers");

                AirtableListRecordsResponse <ViewersTable> response = await task;

                if (response.Success)
                {
                    var viewers = new List <ViewersTable>();
                    var records = response.Records.ToList();
                    foreach (var rec in records)
                    {
                        var viewer = new ViewersTable
                        {
                            Name             = rec.Fields.Name,
                            PreferredPronoun = rec.Fields.PreferredPronoun,
                            EmailAddress     = rec.Fields.EmailAddress,
                            StreamersWatched = rec.Fields.StreamersWatched
                        };
                        viewers.Add(viewer);
                    }

                    var distinctViewers = viewers.GroupBy(g => new { g.EmailAddress });
                    count = distinctViewers.Count();
                }
            }

            return(count);
        }
        public async Task ListRecordsMethodAsync(AirtableBase airtableBase, string offset)
        {
            Task <AirtableListRecordsResponse> task = airtableBase.ListRecords(
                tablename,
                offset,
                fieldsArray,
                filterByFormula,
                maxRecords,
                pageSize,
                sort,
                view);

            response = await task;


            if (response.AirtableApiError.ErrorMessage != null)
            {
                // Error reporting
                errorMessageString = response.AirtableApiError.DetailedErrorMessage2;
            }
            else
            {
                // Do something with the retrieved 'records' and the 'offset'
                // for the next page of the record list.
            }
        }
Example #4
0
        public async Task ListAllLogs_ShouldReturn_ServiceResponseWithBoolTrue_WhenSucessful()
        {
            //Arrange

            //AirtableRecord airtableRecord = new AirtableRecord();
            //airtableRecord.Fields.Add("Summary", "Test");
            //airtableRecord.Fields.Add("Message", "Test");


            //List<AirtableRecord> airtableRecords = new List<AirtableRecord>() { airtableRecord };

            //var airtableListRecordsResponseMock = Mock.Of<AirtableListRecordsResponse>(m =>
            //                               m.Success == true &&
            //                               m.Records == airtableRecords);


            AirtableListRecordsResponse airtableListRecordsResponse = new AirtableListRecordsResponse(new AirtableRecordList());

            airtableRepo.Setup(x => x.ListRecordsAsAsync()).ReturnsAsync(airtableListRecordsResponse);
            //Act
            ServiceResponse <List <LogMessage> > result = await _sut.ListAllLogs();

            //Assert
            Assert.True(result.Sucess);
        }
        // STATUS [ July 13, 2019 ] : this works
        /// <summary>
        ///     Get all the records from a given table
        /// </summary>
        /// <remarks>
        ///     Configuration for each table is setup in Startup.cs and airtableConfiguration.json
        ///     See: https://github.com/ngocnicholas/airtable.net
        /// </remarks>
        /// <param name="tableName">
        ///     Equivalent to the TableName in airtableConfiguration.json
        ///     Equivalent to the tab name in actual airtable
        /// </param>
        /// <param name="tableAuthenticationString">
        ///     Equivalent to the AuthenticationString in airtableConfiguration.json
        /// </param>
        /// <example>
        ///     var listOfRecords = await _atM.GetAllRecordsFromAirtableAsync(_spRankingsConfiguration.TableName, _spRankingsConfiguration.AuthenticationString);
        /// </example>
        public async Task <List <AirtableRecord> > GetAllRecordsFromAirtableAsync(string tableName, string tableAuthenticationString)
        {
            string offset                 = null;
            string errorMessage           = null;
            List <AirtableRecord> records = new List <AirtableRecord>();

            using (AirtableBase airtableBase = new AirtableBase(_airtableConfig.ApiKey, tableAuthenticationString))
            {
                Task <AirtableListRecordsResponse> task = airtableBase.ListRecords(
                    tableName: tableName
                    );

                AirtableListRecordsResponse airResponse = await task.ConfigureAwait(false);

                if (airResponse.Success)
                {
                    records.AddRange(airResponse.Records.ToList());
                    offset = airResponse.Offset;
                }
                else
                {
                    errorMessage = airResponse.AirtableApiError is AirtableApiException ? airResponse.AirtableApiError.ErrorMessage : "Unknown error";
                }
            }

            if (!string.IsNullOrEmpty(errorMessage))
            {
                C.WriteLine("ERROR");
            }

            return(records);
        }
        public async Task <IActionResult> OnGetAsync()
        {
            Names = new List <string>();

            AirtableListRecordsResponse response = await getAirtableData();

            return(Page());
        }
Example #7
0
        public static async Task <bool> CheckHasPlayedSet(SdlPlayer player)
        {
            string offset                 = null;
            string errorMessage           = null;
            List <AirtableRecord> records = new List <AirtableRecord>();

            using (AirtableBase airtableBase = new AirtableBase(Globals.BotSettings.AppKey, Globals.BotSettings.BaseId))
            {
                do
                {
                    Logger.Info($"Retrieving data with offset {offset}.");

                    Task <AirtableListRecordsResponse> task = airtableBase.ListRecords(
                        "Draft Log",
                        offset,
                        null,
                        null,
                        null,
                        null
                        );

                    AirtableListRecordsResponse response = await task;

                    if (response.Success)
                    {
                        Logger.Info($"Success! Continuing with offset \"{response.Offset}\"");
                        records.AddRange(response.Records.ToList());
                        offset = response.Offset;
                    }
                    else if (response.AirtableApiError != null)
                    {
                        errorMessage = response.AirtableApiError.ErrorMessage;
                        break;
                    }
                    else
                    {
                        errorMessage = "Unknown error";
                        break;
                    }
                } while (offset != null);
            }

            if (!string.IsNullOrEmpty(errorMessage))
            {
                SdlAirTableException airTableException = new SdlAirTableException(
                    errorMessage, SdlAirTableException.AirtableErrorType.CommunicationError);
                Logger.Error(airTableException);
                throw airTableException;
            }

            return(records.Any(x =>
                               ((JArray)x.Fields["Alpha Players"]).Any(y => y.Value <string>() == player.AirtableId) ||
                               ((JArray)x.Fields["Bravo Players"]).Any(y => y.Value <string>() == player.AirtableId)));
        }
Example #8
0
        public async Task ListAllLogs_ShouldReturn_ServiceResponseWithBoolFalse_WhenFailed()
        {
            //Arrange
            AirtableListRecordsResponse airtableListRecordsResponse = new AirtableListRecordsResponse(new AirtableBadRequestException());

            airtableRepo.Setup(x => x.ListRecordsAsAsync()).ReturnsAsync(airtableListRecordsResponse);
            //Act
            ServiceResponse <List <LogMessage> > result = await _sut.ListAllLogs();

            //Assert
            Assert.False(result.Sucess);
        }
Example #9
0
        private static async Task <List <AirtableRecord> > GetAirTableDataAsync(string table, List <string> fields, string view = null)
        {
            string offset       = null;
            string errorMessage = null;
            var    records      = new List <AirtableRecord>();

            using (AirtableBase airtableBase = new AirtableBase(appKey, baseId))
            {
                //
                // Use 'offset' and 'pageSize' to specify the records that you want
                // to retrieve.
                // Only use a 'do while' loop if you want to get multiple pages
                // of records.
                //

                do
                {
                    Task <AirtableListRecordsResponse> task = airtableBase.ListRecords(
                        table, offset, fields, null, null, null, null, view);

                    AirtableListRecordsResponse response = await task;

                    if (response.Success)
                    {
                        records.AddRange(response.Records.ToList());
                        offset = response.Offset;
                    }
                    else if (response.AirtableApiError is AirtableApiException)
                    {
                        errorMessage = response.AirtableApiError.ErrorMessage;
                        break;
                    }
                    else
                    {
                        errorMessage = "Unknown error";
                        break;
                    }
                } while (offset != null);
            }

            if (!string.IsNullOrEmpty(errorMessage))
            {
                // Error reporting
                throw new Exception(errorMessage);
            }
            else
            {
                // Do something with the retrieved 'records' and the 'offset'
                // for the next page of the record list.
                return(records);
            }
        }
Example #10
0
        private static async Task <AirtableRecord[]> GetAllPlayerRecords()
        {
            string offset                 = null;
            string errorMessage           = null;
            List <AirtableRecord> records = new List <AirtableRecord>();

            using (AirtableBase airtableBase = new AirtableBase(Globals.BotSettings.AppKey, Globals.BotSettings.BaseId))
            {
                do
                {
                    Logger.Info($"Retrieving data with offset {offset}.");

                    Task <AirtableListRecordsResponse> task = airtableBase.ListRecords(
                        "Draft Standings",
                        offset,
                        null,
                        null,
                        null,
                        null
                        );

                    AirtableListRecordsResponse response = await task;

                    if (response.Success)
                    {
                        Logger.Info($"Success! Continuing with offset \"{response.Offset}\"");
                        records.AddRange(response.Records.ToList());
                        offset = response.Offset;
                    }
                    else if (response.AirtableApiError != null)
                    {
                        errorMessage = response.AirtableApiError.ErrorMessage;
                        break;
                    }
                    else
                    {
                        errorMessage = "Unknown error";
                        break;
                    }
                } while (offset != null);
            }

            if (!string.IsNullOrEmpty(errorMessage))
            {
                SdlAirTableException airTableException = new SdlAirTableException(
                    errorMessage, SdlAirTableException.AirtableErrorType.CommunicationError);
                Logger.Error(airTableException);
                throw airTableException;
            }

            return(records.ToArray());
        }
Example #11
0
        const string API_KEY = "keyvJVU4lZksGnWhI";     // airtable api key for tests

        public static ATTable GetData(string APPLICATION_ID, string TABLE_NAME)
        {
            string  BASE_URL = $"https://api.airtable.com/v0/{APPLICATION_ID}/{Uri.EscapeUriString(TABLE_NAME)}";
            ATTable at       = new ATTable(TABLE_NAME);

            try
            {
                AirtableBase airtableBase = new AirtableBase(API_KEY, APPLICATION_ID);

                var task = airtableBase.ListRecords(TABLE_NAME);

                TaskHelper.RunTaskSynchronously(task);

                AirtableListRecordsResponse response = task.Result;

                if (null == response || response.Records == null)
                {
                    return(at);
                }

                foreach (AirtableRecord rd in response.Records)
                {
                    int   index = int.Parse(rd.GetField("Index").ToString());
                    ATRow row   = new ATRow(index, TABLE_NAME);

                    IEnumerable <AirtableAttachment> attaches = rd.GetAttachmentField("Photo");
                    if (null != attaches && attaches.Count() > 0)
                    {
                        row.PhotoAttach = attaches.First();
                    }

                    foreach (KeyValuePair <string, object> pair in rd.Fields)
                    {
                        if (pair.Key != "Index" && pair.Key != "Photo")
                        {
                            row.Descriptions.Add(pair.Value.ToString());
                        }
                    }

                    if (!row.IsEmpty())
                    {
                        at.Rows.Add(row);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            return(at);
        }
Example #12
0
        public async Task <List <ResponseModel> > GetRecords(string appKey, string baseId)
        {
            var records = new List <AirtableRecord>();

            using AirtableBase airtableBase = new AirtableBase(appKey, baseId);

            Task <AirtableListRecordsResponse> task = airtableBase.ListRecords("Messages");

            AirtableListRecordsResponse response = await task;

            if (response.Success)
            {
                records.AddRange(response.Records.ToList());
            }
            else if (response.AirtableApiError is AirtableApiException)
            {
                throw new InvalidOperationException(response.AirtableApiError.ErrorMessage);
            }
            else
            {
                throw new InvalidOperationException("Unknown error");
            }

            var responseList = new List <ResponseModel>();

            foreach (var record in records)
            {
                if (record.Fields != null && RecordHasFields(record))
                {
                    var recordReponse = new ResponseModel
                    {
                        ID    = record.Fields["id"].ToString(),
                        Title = record.Fields["Summary"].ToString(),
                        Text  = record.Fields["Message"].ToString(),
                    };
                    DateTime.TryParse(record.Fields["receivedAt"].ToString(), out var receivedAt);
                    recordReponse.ReceivedAt = receivedAt.ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
                    responseList.Add(recordReponse);
                }
            }

            return(responseList);
        }
Example #13
0
        //============================== GET ALL ===============================
        public async Task <AirtableListRecordsResponse> GetAll()
        {
            string offset = null;
            IEnumerable <string> fields        = null;
            string             filterByFormula = null;
            int?               maxRecords      = 100;
            int?               pageSize        = 100;
            IEnumerable <Sort> sort            = null;
            string             view            = null;

            var records = new List <AirtableRecord>();

            using (AirtableBase airtableBase = new AirtableBase(appKey, baseId))
            {
                Task <AirtableListRecordsResponse> task = airtableBase.ListRecords(
                    tableName,
                    offset,
                    fields,
                    filterByFormula,
                    maxRecords,
                    pageSize,
                    sort,
                    view);

                AirtableListRecordsResponse response = await task;
                if (response.Success)
                {
                    records.AddRange(response.Records.ToList());
                    offset = response.Offset;
                }
                else if (response.AirtableApiError is AirtableApiException)
                {
                    errorMessage = response.AirtableApiError.ErrorMessage;
                }
                else
                {
                    errorMessage = "Unknown error";
                }
                return(response);
            }
        }
Example #14
0
        public async Task <IReadOnlyList <RecordModel> > GetRecords(int limit)
        {
            _logger.LogTrace($"{GetType()} - BEGIN {nameof(GetRecords)} with limit:{limit}");

            string             errorMessage = "";
            string             offset;
            List <RecordModel> results = new List <RecordModel>();

            using (AirtableBase airtableBase = new AirtableBase(_config.ApiKey, _config.DatabaseId))
            {
                do
                {
                    AirtableListRecordsResponse res = await airtableBase.ListRecords(_config.TableName, view : _config.ViewName, maxRecords : limit);

                    if (res.Success)
                    {
                        results.AddRange(_mapper.ProjectTo <RecordModel>(res.Records.AsQueryable()));
                        offset = res.Offset;
                    }
                    else if (res.AirtableApiError is AirtableApiException)
                    {
                        errorMessage = res.AirtableApiError.ErrorMessage;
                        break;
                    }
                    else
                    {
                        errorMessage = "Unknown error";
                        break;
                    }
                } while (offset != null);
            }

            if (!string.IsNullOrEmpty(errorMessage))
            {
                _logger.LogError(errorMessage);
            }

            return(results);
        }
        public async Task <AirtableListRecordsResponse> getAirtableData()
        {
            string offset       = null;
            string errorMessage = null;
            var    records      = new List <AirtableRecord>();


            AirtableBase airtableBase = new AirtableBase(appKey, baseId);

            Task <AirtableListRecordsResponse> task = airtableBase.ListRecords(
                "People",
                offset);
            AirtableListRecordsResponse response = await task;

            if (response.Success)
            {
                System.Diagnostics.Debug.WriteLine("SUCCESS!!! We received a response.");
                records.AddRange(response.Records.ToList());
                offset = response.Offset;
            }
            else if (response.AirtableApiError is AirtableApiException)
            {
                errorMessage = response.AirtableApiError.ErrorMessage;
            }
            else
            {
                errorMessage = "Unknown error";
            }

            foreach (var r in records)
            {
                string theName = r.GetField("Name").ToString();
                Names.Add(theName);
                System.Diagnostics.Debug.WriteLine("RECORD: " + Names.Last());
            }

            return(response);
        }
Example #16
0
        public async Task <List <string> > GetRecordsFromFormula(string table, string formula)
        {
            string         offset       = null;
            string         errorMessage = null;
            var            records      = new List <AirtableRecord>();
            AirtableRecord myRecord     = new AirtableRecord();

            using (AirtableBase airtableBase = new AirtableBase(ApiKey, BaseId)) {
                Task <AirtableListRecordsResponse> task = airtableBase.ListRecords(
                    table, offset, null, formula);

                AirtableListRecordsResponse response = await task;

                if (response.Success)
                {
                    records.AddRange(response.Records.ToList());
                    offset = response.Offset;
                }
                else if (response.AirtableApiError is AirtableApiException)
                {
                    errorMessage = response.AirtableApiError.GetBaseException().Message;
                }
                else
                {
                    errorMessage = "Unknown error";
                }
            }
            List <string> jsonRecords = new List <string>();

            foreach (AirtableRecord record in records)
            {
                var jsonRec = JsonConvert.SerializeObject(record);
                jsonRecords.Add(jsonRec);
            }

            return(jsonRecords);
        }
Example #17
0
        //async method for listing records
        public async Task ListRecordsMethodAsync(AirtableBase airtableBase, string offset, IGH_DataAccess DA)
        {
            do
            {
                Task <AirtableListRecordsResponse> task = airtableBase.ListRecords(
                    tablename,
                    offset,
                    fieldsArray,
                    filterByFormula,
                    maxRecords,
                    pageSize,
                    sort,
                    view);

                AirtableListRecordsResponse response = await task;
                task.Wait();
                errorMessageString = task.Status.ToString();

                if (response.Success)
                {
                    errorMessageString = "Success!";//change Error Message to success here
                    records.AddRange(response.Records.ToList());
                    offset = response.Offset;
                }
                else if (response.AirtableApiError is AirtableApiException)
                {
                    errorMessageString = response.AirtableApiError.ErrorMessage;
                    break;
                }
                else
                {
                    errorMessageString = "Unknown error";
                    break;
                }
            } while (offset != null);
        }
        // Run every 6 hours
        public static async Task RunAsync([TimerTrigger("0 0 */6 * * *")] TimerInfo myTimer, ILogger log, ExecutionContext context)
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            string baseId    = config["BaseId"];
            string appKey    = config["AppKey"];
            string tableName = config["TableName"];
            string storageConnectionString = config["StorageConnectionString"];
            string blobContainerName       = config["BlobContainerName"];
            string fileName     = "tableData.json";
            string offset       = null;
            string errorMessage = null;
            var    records      = new List <AirtableRecord>();

            using (AirtableBase airtableBase = new AirtableBase(appKey, baseId))
            {
                do
                {
                    Task <AirtableListRecordsResponse> task = airtableBase.ListRecords(
                        tableName,
                        offset,
                        null,
                        null,
                        100000,
                        100,
                        null,
                        null);

                    AirtableListRecordsResponse response = await task;

                    if (response.Success)
                    {
                        records.AddRange(response.Records.ToList());
                        offset = response.Offset;
                        await WriteToBlobStorage(storageConnectionString, blobContainerName, fileName, records);
                    }
                    else if (response.AirtableApiError is AirtableApiException)
                    {
                        errorMessage = response.AirtableApiError.ErrorMessage;
                        break;
                    }
                    else
                    {
                        errorMessage = "Unknown error";
                        break;
                    }
                } while (offset != null);
            }

            if (!string.IsNullOrEmpty(errorMessage))
            {
                // Error reporting
            }
            else
            {
                // Do something with the retrieved 'records' and the 'offset'
                // for the next page of the record list.
            }
        }
Example #19
0
        private async void button1_Click(object sender, EventArgs e)
        {
            //AirtableListRecordsResponse res;
            //AirtableBase airtable = new AirtableBase(AirtableKey, AirtableBase);
            //try
            //{
            //    res = airtable.ListRecords("Match").Result;
            //}
            //catch (Exception ex)
            //{
            //    textBox1.Text = ex.Message;
            //    return;
            //}
            //textBox1.Text = "";
            //foreach (AirtableRecord ar in res.Records)
            //{
            //    textBox1.Text += ar.ToString();
            //    textBox1.Text += "\r\n";
            //}
            //textBox1.Text += "--- Done ---";


            string offset       = null;
            string errorMessage = null;
            string eventKey     = "2020test";
            var    records      = new List <AirtableRecord>();

            using (AirtableBase airtableBase = new AirtableBase(AirtableKey, AirtableBase))
            {
                // Use 'offset' and 'pageSize' to specify the records that you want
                // to retrieve.
                // Only use a 'do while' loop if you want to get multiple pages
                // of records.

                do
                {
                    Task <AirtableListRecordsResponse> task = airtableBase.ListRecords(
                        "Match",
                        offset,
                        null /*fieldsArray*/,
                        $"EventKey='{eventKey}'" /*filterByFormula*/,
                        null /*maxRecords*/,
                        null /*pageSize*/,
                        null /*sort*/,
                        null /*view*/);

                    AirtableListRecordsResponse response = await task;

                    if (response.Success)
                    {
                        records.AddRange(response.Records.ToList());
                        offset = response.Offset;
                    }
                    else if (response.AirtableApiError is AirtableApiException)
                    {
                        errorMessage = response.AirtableApiError.ErrorMessage;
                        break;
                    }
                    else
                    {
                        errorMessage = "Unknown error";
                        break;
                    }
                } while (offset != null);
            }

            if (!string.IsNullOrEmpty(errorMessage))
            {
                textBox1.Text = errorMessage;
            }
            else
            {
                foreach (AirtableRecord ar in records)
                {
                    bool addComma = false;
                    textBox1.AppendText("{");
                    foreach (KeyValuePair <string, object> kv in ar.Fields)
                    {
                        if (addComma)
                        {
                            textBox1.AppendText(",");
                        }
                        addComma = true;
                        textBox1.AppendText($"\"{kv.Key}\":");
                        switch (Type.GetTypeCode(kv.Value.GetType()))
                        {
                        case TypeCode.String:
                            textBox1.AppendText($"\"{kv.Value}\"");
                            break;

                        default:
                            textBox1.AppendText($"{kv.Value}");
                            break;
                        }
                    }
                    textBox1.AppendText("}\r\n");
                }
            }
        }
        public async Task <HttpResponseMessage> GetAll()
        {
            AirtableListRecordsResponse records = await airtableService.GetAll();

            return(Request.CreateResponse(HttpStatusCode.OK, records));
        }
Example #21
0
        private static async Task <AirtableRecord> GetPlayerRecord(ulong discordId)
        {
            string offset                 = null;
            string errorMessage           = null;
            List <AirtableRecord> records = new List <AirtableRecord>();

            using (AirtableBase airtableBase = new AirtableBase(Globals.BotSettings.AppKey, Globals.BotSettings.BaseId))
            {
                do
                {
                    Logger.Info($"Retrieving data with offset {offset}.");

                    Task <AirtableListRecordsResponse> task = airtableBase.ListRecords(
                        "Draft Standings",
                        offset,
                        null,
                        null,
                        null,
                        null
                        );

                    AirtableListRecordsResponse response = await task;

                    if (response.Success)
                    {
                        Logger.Info($"Success! Continuing with offset \"{response.Offset}\"");
                        records.AddRange(response.Records.ToList());
                        offset = response.Offset;
                    }
                    else if (response.AirtableApiError != null)
                    {
                        errorMessage = response.AirtableApiError.ErrorMessage;
                        break;
                    }
                    else
                    {
                        errorMessage = "Unknown error";
                        break;
                    }
                } while (offset != null);
            }

            if (!string.IsNullOrEmpty(errorMessage))
            {
                SdlAirTableException airTableException = new SdlAirTableException(
                    errorMessage, SdlAirTableException.AirtableErrorType.CommunicationError);
                Logger.Error(airTableException);
                throw airTableException;
            }

            Logger.Info("Searching for needed player id.");

            try
            {
                records = records.Where(e => e.Fields["DiscordID"].ToString() == discordId.ToString()).ToList();

                if (records.Count > 1)
                {
                    SdlAirTableException dupeAirtableException = new SdlAirTableException(
                        $"There are multiple records in the Draft Standings table with the id {discordId}!",
                        SdlAirTableException.AirtableErrorType.UnexpectedDuplicate);
                    Logger.Error(dupeAirtableException);
                    throw dupeAirtableException;
                }

                if (records.Count == 0)
                {
                    SdlAirTableException noneAirTableException = new SdlAirTableException(
                        $"There are no players registered with the discord id {discordId}!",
                        SdlAirTableException.AirtableErrorType.NotFound);

                    Logger.Warn(noneAirTableException);
                    throw noneAirTableException;
                }

                return(records.First());
            }
            catch (Exception e)
            {
                if (!(e is SdlAirTableException sdlAirTableException))
                {
                    sdlAirTableException = new SdlAirTableException(
                        e.Message, SdlAirTableException.AirtableErrorType.Generic);
                }

                Logger.Error(sdlAirTableException);
                throw sdlAirTableException;
            }
        }
Example #22
0
        public static async Task <Stage[]> GetMapList()
        {
            string offset                 = null;
            string errorMessage           = null;
            List <AirtableRecord> records = new List <AirtableRecord>();

            using (AirtableBase airtableBase = new AirtableBase(Globals.BotSettings.AppKey, Globals.BotSettings.BaseId))
            {
                do
                {
                    Logger.Info($"Retrieving data with offset {offset}.");

                    Task <AirtableListRecordsResponse> task = airtableBase.ListRecords(
                        "Map List",
                        offset,
                        null,
                        null,
                        null,
                        null
                        );

                    AirtableListRecordsResponse response = await task;

                    if (response.Success)
                    {
                        Logger.Info($"Success! Continuing with offset \"{response.Offset}\"");
                        records.AddRange(response.Records.ToList());
                        offset = response.Offset;
                    }
                    else if (response.AirtableApiError != null)
                    {
                        errorMessage = response.AirtableApiError.ErrorMessage;
                        break;
                    }
                    else
                    {
                        errorMessage = "Unknown error";
                        break;
                    }
                } while (offset != null);
            }

            if (!string.IsNullOrEmpty(errorMessage))
            {
                SdlAirTableException airTableException = new SdlAirTableException(
                    errorMessage, SdlAirTableException.AirtableErrorType.CommunicationError);
                Logger.Error(airTableException);
                throw airTableException;
            }

            List <Stage> resultStages = new List <Stage>();

            foreach (AirtableRecord airtableRecord in records)
            {
                string mapInfo  = airtableRecord.Fields["Name"].ToString();
                string mapName  = mapInfo.Substring(0, mapInfo.Length - 3);
                string modeInfo = mapInfo.Substring(mapInfo.Length - 2);

                Stage currentStage = new Stage
                {
                    MapName = mapName,
                    Mode    = Stage.GetModeFromAcronym(modeInfo)
                };

                resultStages.Add(currentStage);
            }

            return(resultStages.ToArray());
        }
Example #23
0
        public async Task <AirtableListRecordsResponse> ListRecords(
            string tableName,
            string offset = null,
            IEnumerable <string> fields = null,
            string filterByFormula      = null,
            int?maxRecords          = null,
            int?pageSize            = null,
            IEnumerable <Sort> sort = null,
            string view             = null)
        {
            string errorMessage = null;
            var    records      = new List <AirtableRecord>();
            AirtableListRecordsResponse response = null;

            using (AirtableBase airtableBase = new AirtableBase(appKey, baseId))
            {
                //
                // Use 'offset' and 'pageSize' to specify the records that you want
                // to retrieve.
                // Only use a 'do while' loop if you want to get multiple pages
                // of records.
                //

                do
                {
                    Task <AirtableListRecordsResponse> task = airtableBase.ListRecords(
                        tableName,
                        offset,
                        fields,
                        filterByFormula,
                        maxRecords,
                        pageSize,
                        sort,
                        view);

                    response = await task;

                    if (response.Success)
                    {
                        records.AddRange(response.Records.ToList());
                        offset = response.Offset;
                    }
                    else if (response.AirtableApiError is AirtableApiException)
                    {
                        errorMessage = response.AirtableApiError.ErrorMessage;
                        break;
                    }
                    else
                    {
                        errorMessage = "Unknown error";
                        break;
                    }
                } while (offset != null);
            }

            if (!string.IsNullOrEmpty(errorMessage))
            {
                // Error reporting
            }
            else
            {
                // Do something with the retrieved 'records' and the 'offset'
                // for the next page of the record list.
            }
            return(response);
        }