Exemplo n.º 1
0
        public async Task <ResponseModel> AddRecord(RequestModel request, string appKey, string baseId)
        {
            var responseModel = new ResponseModel
            {
                ID         = Utilities.GenerateID(),
                Title      = request.Title,
                Text       = request.Text,
                ReceivedAt = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"),
            };

            using AirtableBase airtableBase = new AirtableBase(appKey, baseId);
            var fields = new Fields();

            fields.AddField("id", responseModel.ID);
            fields.AddField("Summary", responseModel.Title);
            fields.AddField("Message", responseModel.Text);
            fields.AddField("receivedAt", responseModel.ReceivedAt);

            Task <AirtableCreateUpdateReplaceRecordResponse> task = airtableBase.CreateRecord("Messages", fields);

            AirtableCreateUpdateReplaceRecordResponse response = await task;

            if (response.Success)
            {
                return(responseModel);
            }
            else if (response.AirtableApiError is AirtableApiException)
            {
                throw new InvalidOperationException(response.AirtableApiError.ErrorMessage);
            }
            else
            {
                throw new InvalidOperationException("Unknown error");
            }
        }
Exemplo n.º 2
0
        //

        public async Task <bool> LoopTasks()
        {
            AirtableBase airtableBase = new AirtableBase(appKey, baseID);
            var          tasks        = new List <Task <AirtableRetrieveRecordResponse> >();

            foreach (string stringID in stringIDs)
            {
                if (stringID != null)
                {
                    Task <AirtableDeleteRecordResponse> task = airtableBase.DeleteRecord(tablename, stringID);
                    response = await task;
                    if (response.Success)
                    {
                        errorMessage = "Success!";
                    }
                    else
                    {
                        errorMessage = response.AirtableApiError.ErrorMessage;
                    }
                }
                else
                {
                    errorMessage = response.AirtableApiError.DetailedErrorMessage2;
                }
            }
            return(true);
        }
Exemplo n.º 3
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.º 4
0
        public ThingsData(IConfiguration config)
        {
            var baseId = config.GetValue <string>("AirtableBaseId");
            var apiKey = config.GetValue <string>("AirtableApiKey");

            Airtable = new AirtableBase(apiKey, baseId);
        }
Exemplo n.º 5
0
        public async Task <AirtableRetrieveRecordResponse> GetRecordMethodAsync(AirtableBase airtableBase, String stringIDparam)
        {
            Task <AirtableRetrieveRecordResponse> task = airtableBase.RetrieveRecord(tablename, stringIDparam);

            response = await task;
            return(response);
        }
Exemplo n.º 6
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.º 7
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.º 8
0
        public Task <Object> Handle(AddInvoiceExceptionRecordToAirtableCommand request, CancellationToken cancellationToken)
        {
            const string airtableApiKey          = "keyouw8CITeZrgZqx";
            const string invoiceExceptionBaseKey = "appq4DBeNHZdRSoa1";

            var airTableBase = new AirtableBase(airtableApiKey, invoiceExceptionBaseKey);

            var airtableFields = new Fields();

            if (request.FlaggedJob != null)
            {
                airtableFields.FieldsCollection.Add("job_id", request.FlaggedJob.FlaggedJobId.ToString());
                airtableFields.FieldsCollection.Add("flagged_material_code", request.FlaggedJob.FlaggedMaterialCode);
                airtableFields.FieldsCollection.Add("technician_name", request.FlaggedJob.TechnicianName);
                airtableFields.FieldsCollection.Add("job_completed_date", DateTime.Parse(request.FlaggedJob.JobCompletedDate));
                airtableFields.FieldsCollection.Add("job_url", "https://go.servicetitan.com/#/Job/Index/" + request.FlaggedJob.FlaggedJobId.ToString());
                airtableFields.FieldsCollection.Add("service_code", request.FlaggedJob.ServiceCode);
            }
            if (request.InvoiceError != null)
            {
                airtableFields.FieldsCollection.Add("job_id", request.InvoiceError.FlaggedJobId.ToString());
                airtableFields.FieldsCollection.Add("flagged_material_code", request.InvoiceError.FlaggedMaterialCode);
                airtableFields.FieldsCollection.Add("technician_name", request.InvoiceError.TechnicianName);
                airtableFields.FieldsCollection.Add("job_completed_date", DateTime.Parse(request.InvoiceError.JobCompletedDate));
                airtableFields.FieldsCollection.Add("job_url", "https://go.servicetitan.com/#/Job/Index/" + request.InvoiceError.FlaggedJobId.ToString());
                airtableFields.FieldsCollection.Add("service_code", request.InvoiceError.ServiceCode);
            }

            var result = airTableBase.CreateRecord("exception_list", airtableFields, true).Result;


            return(Task.FromResult <Object>(result));
        }
Exemplo n.º 9
0
        public async Task <(bool, string)> PostAttachmentToRecord(string magazineCoverUrl, string table, string recordId)
        {
            AirtableAttachment attachment = new AirtableAttachment()
            {
                Url = magazineCoverUrl
            };
            List <AirtableAttachment> attachmentList = new List <AirtableAttachment> {
                attachment
            };

            using (AirtableBase airtableBase = new AirtableBase(ApiKey, BaseId)) {
                var fields = new Fields();
                fields.AddField("Cover", attachmentList);

                var task = airtableBase.UpdateRecord(table, fields, recordId);

                var response = await task;

                if (response.Success)
                {
                    return(true, null);
                }
                else if (response.AirtableApiError is AirtableApiException)
                {
                    return(false, response.AirtableApiError.GetBaseException().Message);
                }
                else
                {
                    return(false, "Unknown error");
                }
            }
        }
Exemplo n.º 10
0
        public static async Task ReportScores(Set set, double gain, double loss)
        {
            using (AirtableBase airtableBase = new AirtableBase(Globals.BotSettings.AppKey, Globals.BotSettings.BaseId))
            {
                Fields fields = new Fields();

                string[] alphaPlayers = set.AlphaTeam.Players.Select(e => e.AirtableId).ToArray();
                string[] bravoPlayers = set.BravoTeam.Players.Select(e => e.AirtableId).ToArray();

                fields.AddField("Date", DateTime.Now);
                fields.AddField("Alpha Players", alphaPlayers);
                fields.AddField("Bravo Players", bravoPlayers);
                fields.AddField("Alpha Score", set.AlphaTeam.Score);
                fields.AddField("Bravo Score", set.BravoTeam.Score);
                fields.AddField("Gain", gain);
                fields.AddField("Loss", loss);
                fields.AddField("A SZ",
                                set.AlphaTeam.OrderedMatchResults
                                .Select((e, index) => new { Score = e, set.Stages[index].Mode })
                                .Where(e => e.Score == 1 && e.Mode == GameMode.SplatZones)
                                .Aggregate(0, (e, f) => e + f.Score));
                fields.AddField("B SZ",
                                set.BravoTeam.OrderedMatchResults
                                .Select((e, index) => new { Score = e, set.Stages[index].Mode })
                                .Where(e => e.Score == 1 && e.Mode == GameMode.SplatZones)
                                .Aggregate(0, (e, f) => e + f.Score));
                fields.AddField("A TC",
                                set.AlphaTeam.OrderedMatchResults
                                .Select((e, index) => new { Score = e, set.Stages[index].Mode })
                                .Where(e => e.Score == 1 && e.Mode == GameMode.TowerControl)
                                .Aggregate(0, (e, f) => e + f.Score));
                fields.AddField("B TC",
                                set.BravoTeam.OrderedMatchResults
                                .Select((e, index) => new { Score = e, set.Stages[index].Mode })
                                .Where(e => e.Score == 1 && e.Mode == GameMode.TowerControl)
                                .Aggregate(0, (e, f) => e + f.Score));
                fields.AddField("A RM",
                                set.AlphaTeam.OrderedMatchResults
                                .Select((e, index) => new { Score = e, set.Stages[index].Mode })
                                .Where(e => e.Score == 1 && e.Mode == GameMode.Rainmaker)
                                .Aggregate(0, (e, f) => e + f.Score));
                fields.AddField("B RM",
                                set.BravoTeam.OrderedMatchResults
                                .Select((e, index) => new { Score = e, set.Stages[index].Mode })
                                .Where(e => e.Score == 1 && e.Mode == GameMode.Rainmaker)
                                .Aggregate(0, (e, f) => e + f.Score));
                fields.AddField("A CB",
                                set.AlphaTeam.OrderedMatchResults
                                .Select((e, index) => new { Score = e, set.Stages[index].Mode })
                                .Where(e => e.Score == 1 && e.Mode == GameMode.ClamBlitz)
                                .Aggregate(0, (e, f) => e + f.Score));
                fields.AddField("B CB",
                                set.BravoTeam.OrderedMatchResults
                                .Select((e, index) => new { Score = e, set.Stages[index].Mode })
                                .Where(e => e.Score == 1 && e.Mode == GameMode.ClamBlitz)
                                .Aggregate(0, (e, f) => e + f.Score));

                await airtableBase.CreateRecord("Draft Log", fields, true);
            }
        }
Exemplo n.º 11
0
        //

        public async Task CreateRecordMethodAsync(AirtableBase airtableBase)
        {
            Task <AirtableCreateUpdateReplaceRecordResponse> task = airtableBase.CreateRecord(tablename, fields, conversion);
            var response = await task;


            OutRecord = response.Record;


            if (response.AirtableApiError.ErrorMessage != null)
            {
                // Error reporting
                errorMessageString = response.AirtableApiError.ErrorMessage;
            }
            else
            {
                // Do something with the retrieved 'record'
                errorMessageString = "Success!";
                OutRecord          = response.Record;
            }

            if (response.Success == true)
            {
                errorMessageString = "Success!";
            }
        }
Exemplo n.º 12
0
        //=========================== CREATE/POST ===========================================
        public async Task <AirtableCreateUpdateReplaceRecordResponse> Create(RecordCreateRequest req)
        {
            using (AirtableBase airtableBase = new AirtableBase(appKey, baseId))
            {
                var fields = new Fields();
                fields.AddField("Title", req.Title);
                fields.AddField("Priority", req.Priority);
                fields.AddField("Status", req.Status);
                fields.AddField("Due Date", req.DueDate);

                AirtableCreateUpdateReplaceRecordResponse response = await airtableBase.CreateRecord(tableName, fields, true);

                if (!response.Success)
                {
                    if (response.AirtableApiError is AirtableApiException)
                    {
                        errorMessage = response.AirtableApiError.ErrorMessage;
                    }
                    else
                    {
                        errorMessage = "Unknown error";
                    }
                    // Report errorMessage
                }
                else
                {
                    // Do something with your created record.
                    Console.WriteLine("ok");
                }
                return(response);
            }
        }
Exemplo n.º 13
0
        public async Task <AirtableCreateUpdateReplaceRecordResponse> UpdateRecord(RecordUpdateRequest req)
        {
            using (AirtableBase airtableBase = new AirtableBase(appKey, baseId))
            {
                var fields = new Fields();
                fields.AddField("Title", req.Title);
                fields.AddField("Priority", req.Priority);
                fields.AddField("Status", req.Status);
                fields.AddField("Due Date", req.DueDate);

                AirtableCreateUpdateReplaceRecordResponse response = await airtableBase.UpdateRecord(tableName, fields, req.Id.ToString());

                //var response = await task;

                if (!response.Success)
                {
                    string errorMessage = null;
                    if (response.AirtableApiError is AirtableApiException)
                    {
                        errorMessage = response.AirtableApiError.ErrorMessage;
                    }
                    else
                    {
                        errorMessage = "Unknown error";
                    }
                    // Report errorMessage
                }
                else
                {
                    var record = response.Record;
                    // Do something with your updated record.
                }
                return(response);
            }
        }
Exemplo n.º 14
0
        public async Task <string> GetRecord(string table, string recordId)
        {
            string         errorMessage = null;
            var            records      = new List <AirtableRecord>();
            AirtableRecord myRecord     = new AirtableRecord();

            using (AirtableBase airtableBase = new AirtableBase(ApiKey, BaseId)) {
                var response = await airtableBase.RetrieveRecord(table, recordId);

                if (response.Success)
                {
                    myRecord = response.Record;
                }
                else if (response.AirtableApiError is AirtableApiException)
                {
                    errorMessage = response.AirtableApiError.GetBaseException().Message;
                }
                else
                {
                    errorMessage = "Error!";
                }
            }
            var responseJson = JsonConvert.SerializeObject(myRecord);

            return(responseJson);
        }
Exemplo n.º 15
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.º 16
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.º 17
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.º 18
0
        private SolveResults ListRecordsSolve(AirtableBase airtableBase, IGH_DataAccess DA)
        {
            SolveResults result      = new SolveResults();
            string       offset      = "0";
            Task         OutResponse = this.ListRecordsMethodAsync(airtableBase, offset, DA);

            result.Value = 1;
            return(result);
        }
Exemplo n.º 19
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Declare a variable for the input String
            bool data = false;

            // Use the DA object to retrieve the data inside the first input parameter.
            // If the retieval fails (for example if there is no data) we need to abort.
            if (!DA.GetData(0, ref data))
            {
                records.Clear();
                return;
            }
            if (!DA.GetData(1, ref baseID))
            {
                return;
            }
            if (!DA.GetData(2, ref appKey))
            {
                return;
            }
            if (!DA.GetData(3, ref tablename))
            {
                return;
            }
            if (!DA.GetData(4, ref view))
            {
                return;
            }

            // If the retrieved data is Nothing, we need to abort.
            // We're also going to abort on a zero-length String.
            if (data == false)
            {
                records.Clear();
                return;
            }



            AirtableBase airtableBase   = new AirtableBase(appKey, baseID);
            Task         OutResponse    = ListRecordsMethodAsync(airtableBase);
            var          responseString = OutResponse.ToString();

            if (response != null)
            {
                if (response.Records != null)
                {
                    records.AddRange(response.Records.ToList());
                    errorMessageString = "Success!";
                }
            }


            // Use the DA object to assign a new String to the first output parameter.
            DA.SetData(0, errorMessageString);
            DA.SetDataList(1, records);
        }
Exemplo n.º 20
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.º 21
0
        // STATUS [ July 13, 2019 ] : this works
        /// <summary>
        ///     Get one record 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>
        /// <param name="recordId">
        ///     The airtable generated record Id
        ///     This is visible thorugh the API but NOT in the actual table
        ///     It is different than things like "Author_Id", "Record_Id", "Website_Id"
        /// </param>
        /// <example>
        ///     var oneRecord = await _atM.GetOneRecordFromAirtableAsync("SpRankings", authenticationString, "rec7yJqKs5Ht3I7j3");
        /// </example>
        public async Task <AirtableRecord> GetOneRecordFromAirtableAsync(string tableName, string tableAuthenticationString, string recordId)
        {
            using (AirtableBase airtableBase = new AirtableBase(_airtableConfig.ApiKey, tableAuthenticationString))
            {
                Task <AirtableRetrieveRecordResponse> recordTask         = airtableBase.RetrieveRecord(tableName, recordId);
                AirtableRetrieveRecordResponse        recordTaskResponse = await recordTask.ConfigureAwait(false);

                AirtableRecord oneRecord = recordTaskResponse.Record;
                return(oneRecord);
            }
        }
Exemplo n.º 22
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.º 24
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.º 25
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.º 26
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.º 27
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.º 28
0
        public static async Task SetFriendCodeAsync(SdlPlayer player, string code)
        {
            using (AirtableBase airtableBase = new AirtableBase(Globals.BotSettings.AppKey, Globals.BotSettings.BaseId))
            {
                Fields fields = new Fields();
                fields.AddField("Friend Code", code);

                AirtableCreateUpdateReplaceRecordResponse response =
                    await airtableBase.UpdateRecord("Draft Standings", fields, player.AirtableId, true);

                if (!response.Success)
                {
                    Logger.Error(response.AirtableApiError.ErrorMessage);
                }
            }
        }
        public async Task <AirtableCreateUpdateReplaceRecordResponse> CreateRecordAsAsync(LogMessage msg)
        {
            AirtableCreateUpdateReplaceRecordResponse response;

            using (AirtableBase airtableBase = new AirtableBase(appKey, baseId))
            {
                var fields = new Fields();
                fields.AddField(Constants.ID, msg.Id);
                fields.AddField(Constants.SUMMARY, msg.Title);
                fields.AddField(Constants.MESSAGE, msg.Text);
                fields.AddField(Constants.RECEIVEDAT, msg.ReceivedAt);
                Task <AirtableCreateUpdateReplaceRecordResponse> task = airtableBase.CreateRecord("Messages", fields, true);
                response = await task;
            }

            return(response);
        }
Exemplo n.º 30
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            string configPath = @"C:\Temp\AirtableSettings.csv";

            try
            {
                Dictionary <string, Helpers.CardContent> dashboardDictionary = Helpers.ModelStatus(doc);

                List <string> apiAndKeys = Helpers.GetAirtableKeys(configPath);
                string        baseId     = apiAndKeys[0];
                string        appKey     = apiAndKeys[1];

                var fields = new Fields();

                foreach (var dict in dashboardDictionary)
                {
                    fields.AddField(dict.Key, dict.Value.Value);
                }

                AirtableBase airtableBase = new AirtableBase(appKey, baseId);

                //var listRecords = GetRecords(airtableBase, "Model Status", records, errorMessage);
                var create = Helpers.CreateRecord(airtableBase, "Model Status", fields);

                Task.Run(() => create);
                //Task.WaitAll(listRecords, create);
                //Task.WaitAll(create);


                return(Result.Succeeded);
            }

            catch (Exception ex)
            {
                TaskDialog.Show("Error", ex.Message);
                return(Result.Failed);
            }
        }