public async Task <bool> CheckIfRecordExist(ulong id)
        {
            var records = await Base.ListRecords(table, filterByFormula : "{userId} = " + id);

            if (records.Records.Count() != 0)
            {
                return(true);
            }
            return(false);
        }
Exemplo n.º 2
0
        private async void Render(object state)
        {
            using var airtableBase =
                      new AirtableBase(_configuration["Airtable:Key"], _configuration["Airtable:Base"]);
            var response = await airtableBase.ListRecords(
                "Redirections",
                view : "Main", maxRecords : 1);

            if (!response.Success)
            {
                return;
            }

            var records = response.Records
                          .ToDictionary(x => x.Fields["Base Address"].ToString(),
                                        x => new DomainMappingValue
            {
                Desktop = new DomainVariantValue {
                    Url = x.Fields["Desktop Redirection"].ToString()
                },
                Mobile = new DomainVariantValue {
                    Url = x.Fields["Mobile Redirection"].ToString()
                }
            });

            foreach (var record in records)
            {
                record.Value.Mobile.Html = await FillHtmlCache("http://" + record.Value.Mobile.Url);

                record.Value.Desktop.Html = await FillHtmlCache("http://" + record.Value.Desktop.Url);

                _memoryCache.Set(record.Key, record.Value);
            }
        }
Exemplo n.º 3
0
        public async Task <IActionResult> GetCharts(string domainId, DeviceId deviceId)
        {
            using var airtableBase = new AirtableBase(_configuration["Airtable:Key"], _configuration["Airtable:Base"]);
            var redirectedToField = "RedirectedTo";
            var creationTimeField = "CreationTime";
            var records           = await airtableBase.ListRecords("Views",
                                                                   fields : new[] { redirectedToField, creationTimeField },
                                                                   filterByFormula : "AND({BaseDomain}='" + domainId + "', {RedirectedTo}='" +
                                                                   (deviceId == DeviceId.Mobile ? "Mobile" : "Desktop") + "')");

            var typed = records.Records.Select(x =>
            {
                return(new
                {
                    RedirectedTo = x.Fields[redirectedToField],
                    CreationDate = (DateTime)x.Fields[creationTimeField]
                });
            });
            var groupedByDay = typed
                               .GroupBy(x => x.CreationDate.Date)
                               .Select(x => new
            {
                Date  = x.Key,
                Count = x.Count()
            })
                               .ToList();
            var labelStr = string.Join("%2C", groupedByDay.Select(x => "%22" + x.Date.ToString("d") + "%22"));
            var dataStr  = string.Join("%2C", groupedByDay.Select(x => x.Count.ToString()));

            return(Redirect(
                       $"https://quickchart.io/chart?bkg=white&c=%7B%0A%20%20%22type%22%3A%20%22bar%22%2C%0A%20%20%22data%22%3A%20%7B%0A%20%20%20%20%22labels%22%3A%20%5B%0A%20%20%20%20%20%20{labelStr}%0A%20%20%20%20%5D%2C%0A%20%20%20%20%22datasets%22%3A%20%5B%0A%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%22label%22%3A%20%22Redirections%22%2C%0A%20%20%20%20%20%20%20%20%22backgroundColor%22%3A%20%22%23A83400%22%2C%0A%20%20%20%20%20%20%20%20%22data%22%3A%20%5B%0A%20%20%20%20%20%20%20%20%20%20{dataStr}%0A%20%20%20%20%20%20%20%20%5D%0A%20%20%20%20%20%20%7D%0A%20%20%20%20%5D%0A%20%20%7D%0A%7D"));
        }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
0
        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.
            }
        }
Exemplo n.º 6
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);
        }
Exemplo n.º 7
0
        // 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);
        }
Exemplo n.º 8
0
        public async Task <WaifuObject> GetWaifus(ulong id)
        {
            WaifuObject waifu   = new WaifuObject();
            var         records = await Base.ListRecords(table, filterByFormula : "{userId} = " + id);

            foreach (var record in records.Records)
            {
                waifu.Id               = id;
                waifu.RecordId         = record.Id;
                waifu.Feeds            = Convert.ToString(record.GetField("Feeds"));
                waifu.Levels           = Convert.ToString(record.GetField("Levels"));
                waifu.Waifus           = Convert.ToString(record.GetField("Waifus"));
                waifu.Lewds            = Convert.ToString(record.GetField("Lewds"));
                waifu.LastModifiedHour = Convert.ToString(record.GetField("LastModifedHour"));
            }
            return(waifu);
        }
Exemplo n.º 9
0
        public async Task <IActionResult> Get()
        {
            var host      = Request.Host.ToString();
            var isMobile  = _deviceResolver.Device.Type == DeviceType.Mobile;
            var isCrawler = _crawlerResolver.Crawler != null;
            var type      = isMobile ? "Mobile Redirection" : "Desktop Redirection";
            var ip        = HttpContext.Connection.RemoteIpAddress?.ToString();
            var userAgent = Request.Headers["User-Agent"].ToString();
            var referer   = Request.Headers["Referer"].ToString();
            var hasEntry  = _memoryCache.TryGetValue <DomainMappingValue>(host, out var value);

            _ = Task.Run(async() =>
            {
                using var airtableBaseInTask =
                          new AirtableBase(_configuration["Airtable:Key"], _configuration["Airtable:Base"]);
                await airtableBaseInTask.CreateRecord("Views", new Fields
                {
                    FieldsCollection = new Dictionary <string, object>
                    {
                        ["BaseDomain"]   = host,
                        ["Ip"]           = ip,
                        ["UserAgent"]    = userAgent,
                        ["RedirectedTo"] = isMobile ? "Mobile" : "Desktop",
                        ["Referrer"]     = referer
                    }
                });
            });

            if (isCrawler && hasEntry)
            {
                var content = isMobile ? value.Mobile.Html : value.Desktop.Html;
                return(Content(content, "text/html"));
            }
            else
            {
                using var airtableBase =
                          new AirtableBase(_configuration["Airtable:Key"], _configuration["Airtable:Base"]);
                var response = await airtableBase.ListRecords(
                    "Redirections", fields : new[] { type }, filterByFormula : "{Base Address} = '" + host + "'",
                    view : "Main", maxRecords : 1);

                if (!response.Success)
                {
                    return(BadRequest());
                }

                var airtableRecord = response.Records.FirstOrDefault();
                if (airtableRecord == null)
                {
                    return(BadRequest());
                }
                var address = "https://" + airtableRecord.Fields[type];

                return(base.Redirect(address));
            }
        }
Exemplo n.º 10
0
        public async Task <List <BackgroundObject> > GetBackgrounds()
        {
            List <BackgroundObject> backgrounds = new List <BackgroundObject>();
            var records = await Base.ListRecords("Backgrounds");

            foreach (var record in records.Records)
            {
                backgrounds.Add(new BackgroundObject()
                {
                    Name  = Convert.ToString(record.GetField("Name")),
                    Url   = Convert.ToString(record.GetField("url")),
                    Price = Convert.ToInt32(record.GetField("price")),
                    Nitro = Convert.ToBoolean(record.GetField("Nitro")),
                    Dev   = Convert.ToBoolean(record.GetField("Dev"))
                });
            }

            return(backgrounds);
        }
Exemplo n.º 11
0
        public async Task <List <Thing> > GetThingsAsync()
        {
            var response = await Airtable.ListRecords(TABLE_NAME, maxRecords : int.MaxValue);

            if (response.Success)
            {
                return(response.Records.Select(record => new Thing(record)).ToList());
            }

            return(new List <Thing>());
        }
Exemplo n.º 12
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)));
        }
        public async Task <AirtableListRecordsResponse> ListRecordsAsAsync()
        {
            AirtableListRecordsResponse response;

            using (AirtableBase airtableBase = new AirtableBase(appKey, baseId))
            {
                Task <AirtableListRecordsResponse> task = airtableBase.ListRecords("Messages");
                response = await task;
            }

            return(response);
        }
Exemplo n.º 14
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);
            }
        }
Exemplo n.º 15
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());
        }
Exemplo n.º 16
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);
        }
Exemplo n.º 17
0
        public async Task <IActionResult> GetRepartitionChart(string domainId)
        {
            using var airtableBase = new AirtableBase(_configuration["Airtable:Key"], _configuration["Airtable:Base"]);
            var redirectedToField = "RedirectedTo";
            var records           = await airtableBase.ListRecords("Views",
                                                                   fields : new[] { redirectedToField },
                                                                   filterByFormula : "{BaseDomain}='" + domainId + "'");

            var mobileCount  = records.Records.Count(x => x.Fields[redirectedToField].ToString() == "Mobile");
            var desktopCount = records.Records.Count(x => x.Fields[redirectedToField].ToString() == "Desktop");

            return(Redirect(
                       $"https://quickchart.io/chart?bkg=white&c=%7B%0A%20%20type%3A%20%27doughnut%27%2C%0A%20%20data%3A%20%7B%0A%20%20%20%20datasets%3A%20%5B%0A%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20data%3A%20%5B{mobileCount}%2C%20{desktopCount}%5D%2C%0A%20%20%20%20%20%20%20%20backgroundColor%3A%20%5B%0A%20%20%20%20%20%20%20%20%20%20%27%23A83400%27%2C%0A%20%20%20%20%20%20%20%20%20%20%27rgb(255%2C%20159%2C%2064)%27%2C%0A%20%20%20%20%20%20%20%20%5D%2C%0A%20%20%20%20%20%20%20%20label%3A%20%27Dataset%201%27%2C%0A%20%20%20%20%20%20%7D%2C%0A%20%20%20%20%5D%2C%0A%20%20%20%20labels%3A%20%5B%27Mobile%27%2C%20%27Desktop%27%5D%2C%0A%20%20%7D%0A%7D%0A"));
        }
Exemplo n.º 18
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);
        }
Exemplo n.º 19
0
        public static async IAsyncEnumerable <AirtableRecord <T> > Rows <T>(this AirtableBase at, string table, string[] fields = null)
        {
            string offset = null;

            while (true)
            {
                var res = await at.ListRecords <T>(table, offset, fields);

                res.EnsureSuccess();
                foreach (var r in res.Records)
                {
                    yield return(r);
                }
                offset = res.Offset;
                if (offset == null)
                {
                    break;
                }
            }
        }
Exemplo n.º 20
0
        public async Task <IActionResult> AcmeChallenge([FromRoute] string token)
        {
            using (AirtableBase airtableBase = new AirtableBase(_configuration["Airtable:Key"], _configuration["Airtable:Base"]))
            {
                var response = await airtableBase.ListRecords(
                    "Acme", fields : new[] { "Value", "ContentType" }, filterByFormula : "{Token} = '" + token + "'", view : "Main", maxRecords : 1);

                if (response.Success)
                {
                    var airtableRecord = response.Records.FirstOrDefault();
                    if (airtableRecord != null)
                    {
                        return(Content(airtableRecord.Fields["Value"].ToString(),
                                       new MediaTypeHeaderValue(airtableRecord.Fields["ContentType"].ToString())));
                    }
                }
            }

            return(NotFound());
        }
Exemplo n.º 21
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);
            }
        }
Exemplo n.º 22
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 <List <AirtableRecord <Cuisine> > > GetCuisinesAsync()
        {
            // check the cache
            if (_cuisines != null)
            {
                return(_cuisines);
            }

            _cuisines = new List <AirtableRecord <Cuisine> >();
            string offset = null;

            using (AirtableBase airtableBase = new AirtableBase(appKey, baseId))
            {
                do
                {
                    Task <AirtableListRecordsResponse <Cuisine> > task =
                        airtableBase.ListRecords <Cuisine>(tableName: "Cuisines", offset: offset);

                    var response = await task;

                    if (response.Success)
                    {
                        _cuisines.AddRange(response.Records);
                        offset = response.Offset;
                    }
                    else if (response.AirtableApiError is AirtableApiException)
                    {
                        throw new Exception(response.AirtableApiError.ErrorMessage);
                        break;
                    }
                    else
                    {
                        throw new Exception("Unknown error");
                        break;
                    }
                } while (offset != null);
            }
            return(_cuisines);
        }
        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);
        }
Exemplo n.º 25
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);
        }
Exemplo n.º 26
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);
        }
Exemplo n.º 27
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);
        }
Exemplo n.º 28
0
        async private void AirtableFetchRecords()
        {
            string offset       = null;
            string errorMessage = null;
            var    records      = new List <AirtableRecord>();

            using (AirtableBase airtableBase = new AirtableBase(App.AirtableKey, App.AirtableBase))
            {
                do
                {
                    if (offset != null)
                    {
                        // Sleep for half a second so we don't make requests too fast.
                        // The free Airtable plan only allows 5 requests per second.
                        // Each download is 100 records (pagesize).
                        System.Threading.Thread.Sleep(500);
                    }

                    AirtableListRecordsResponse response;
                    response = await airtableBase.ListRecords(
                        "Match",
                        offset,
                        null /*fieldsArray*/,
                        $"EventKey='{App.currFRCEventKey}'" /*filterByFormula*/,
                        null /*maxRecords*/,
                        100 /*pageSize*/,
                        null /*sort*/,
                        null /*view*/);

                    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))
            {
                Label_Results.Text = errorMessage;
                return;
            }

            int RecordCount = 0;
            int NewCount    = 0;
            int UpdateCount = 0;
            int IgnoreCount = 0;

            foreach (AirtableRecord ar in records)
            {
                RecordCount++;
                JObject        jo         = new JObject();
                EventTeamMatch m          = null;
                string         uuid       = ar.Fields["Uuid"].ToString();
                string         airtableId = ar.Id;
                if (!string.IsNullOrEmpty(uuid))
                {
                    StringBuilder query = new StringBuilder();
                    query.Append("SELECT [EventTeamMatch].* FROM [EventTeamMatch]");
                    query.Append(" WHERE [EventTeamMatch].[Uuid] = '");
                    query.Append(uuid);
                    query.Append("'");
                    m = App.Database.GetEventTeamMatchAsyncUuid(uuid);
                    if (m != null && m.Changed >= (long)ar.Fields["Changed"])
                    {
                        // this record is newer, ignore airtable
                        IgnoreCount++;
                        continue;
                    }
                }
                if (m == null)
                {
                    m            = new EventTeamMatch();
                    m.AirtableId = ar.Id;
                    NewCount++;
                }
                else
                {
                    UpdateCount++;
                }
                // convert to JObject and back so individual match fields are not needed here
                jo = m.ToJson();
                foreach (KeyValuePair <string, object> kv in ar.Fields)
                {
                    if (kv.Key == "Id" || kv.Key == "AirtableId")
                    {
                        continue;
                    }
                    int intValue;
                    if (int.TryParse(kv.Value.ToString(), out intValue))
                    {
                        if (kv.Key == "Changed")
                        {
                            // only update if lower
                            if (m.Changed < intValue)
                            {
                                m.Changed = intValue;
                            }
                        }
                        else
                        {
                            jo.SetValue(kv.Key, intValue);
                        }
                    }
                    else
                    {
                        jo.SetValue(kv.Key, kv.Value.ToString());
                    }
                }
                // Rebuild the EventTeamMatch from the JObject data
                m = EventTeamMatch.FromJson(jo);
                if (m.Changed % 2 == 1)
                {
                    m.Changed++;
                }
                // save to the database
                await App.Database.SaveEventTeamMatchAsync(m);
            }

            Label_Results.Text  = "";
            Label_Results.Text += $"Records found: {RecordCount}\r\n";
            Label_Results.Text += $"Records added: {NewCount}\r\n";
            Label_Results.Text += $"Records updated: {UpdateCount}\r\n";
            Label_Results.Text += $"Records ignored: {IgnoreCount}";
        }
Exemplo n.º 29
0
        /// <summary>
        /// overload to accept appkeys and baseid to access more tables.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="AppKey"></param>
        /// <param name="BaseId"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public async Task <List <T> > GetTableAsync <T>(string AppKey, string BaseId, string tableName, string view = null) where T : IAirtable
        {
            var    table      = new List <AirtableRecord <T> >();
            string offset     = null;
            var    retryCount = 0;

            await semaphore.WaitAsync(); // wait for your place in line

            using AirtableBase airtableBase = new AirtableBase(AppKey, BaseId);
            try
            {
                do
                {
                    Task <AirtableListRecordsResponse <T> > task =
                        airtableBase.ListRecords <T>(tableName: tableName, offset: offset, view: view);

                    var response = await task;

                    if (response.Success)
                    {
                        PopulateIds(response.Records);
                        table.AddRange(response.Records);
                        offset = response.Offset;
                    }
                    // look for timeouts and add retry logic.
                    else if (response.AirtableApiError != null)
                    {
                        if (retryCount < 3)
                        {
                            retryCount++;
                            await Task.Delay(500); //pause half-a-sec
                        }
                        else
                        {
                            // too many retrys
                            table = null;
                            break;
                        }
                    }
                } while (offset != null);
            }
            catch (Exception e)
            {
                table = null;
            }
            finally
            {
                semaphore.Release(); // let the next one in
            }

            List <T> list = null;

            if (table != null)
            {
                list = new List <T>();
                try
                {
                    list = (from c in table select c.Fields).ToList();
                }
                catch (Exception e)
                {
                    var err = e.InnerException;
                }
            }

            return(list);
        }
Exemplo n.º 30
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");
                }
            }
        }