public void CanExportArmsAsync_AllArms_ShouldContain_armnum()
        {
            // Arrange
            var apiKey      = _token;
            var apiEndpoint = _uri;

            // Act

            /*
             * Using API Version 1.0.0+
             */
            var redcapApi = new RedcapApi(apiEndpoint);
            var result    = redcapApi.ExportArmsAsync(apiKey, "arm", ReturnFormat.json, null, OnErrorFormat.json).Result;
            var data      = JsonConvert.DeserializeObject(result).ToString();

            // Assert
            // Expecting multiple arms to be return since we asked for all arms by not providing any arms by passing null for the params
            Assert.Contains("1", data);
            Assert.Contains("2", data);
        }
        public void CanDeleteEventsAsync_SingleEvent_ShouldReturn_number()
        {
            // Arrange
            var apiKey                = _token;
            var apiEndpoint           = _uri;
            var DeleteEventsAsyncData = new string[] { "baseline_arm_1" };

            // Act

            /*
             * Using API Version 1.0.0+
             */
            var redcapApi = new RedcapApi(apiEndpoint);
            var result    = redcapApi.DeleteEventsAsync(apiKey, null, null, DeleteEventsAsyncData).Result;
            var data      = JsonConvert.DeserializeObject(result).ToString();

            // Assert
            // Expecting "3", since we had 3 redcap events imported
            Assert.Contains("3", data);
        }
Beispiel #3
0
        /// <summary>
        /// Sends http request to api
        /// </summary>
        /// <param name="redcapApi"></param>
        /// <param name="payload">data </param>
        /// <param name="uri">URI of the api instance</param>
        /// <returns>string</returns>
        public static async Task <string> SendPostRequest(this RedcapApi redcapApi, Dictionary <string, string> payload, Uri uri)
        {
            string responseString;

            using (var handler = GetHttpHandler())
                using (var client = new HttpClient(handler))
                {
                    // Encode the values for payload
                    using (var content = new FormUrlEncodedContent(payload))
                    {
                        using (var response = await client.PostAsync(uri, content))
                        {
                            // check the response and make sure its successful
                            response.EnsureSuccessStatusCode();
                            responseString = await response.Content.ReadAsStringAsync();
                        }
                    }
                }
            return(responseString);
        }
        public void CanSaveRecord1_SingleRecord_ShouldReturn_Ids()
        {
            // Arrange
            var apiKey      = _token;
            var apiEndpoint = _uri;

            var record = new
            {
                record_id         = "1",
                redcap_event_name = "event1_arm_1",
                first_name        = "John",
                last_name         = "Doe"
            };
            // Act
            var redcap_api = new RedcapApi(apiKey, apiEndpoint);
            var result     = redcap_api.SaveRecordsAsync(record, ReturnContent.ids, OverwriteBehavior.overwrite, ReturnFormat.json, RedcapDataType.flat, OnErrorFormat.json).Result;
            var data       = JsonConvert.DeserializeObject(result).ToString();

            // Assert
            Assert.Contains("1", data);
        }
Beispiel #5
0
        /// <summary>
        /// The purpose of this method is to acquire the JSON file from RedCap using the RedCap API
        /// </summary>
        static void AcquireJSONAndMetaData()
        {
            //These lines are for looking at the secrets file and getting the info to make contact with the RedCap API
            var builder = new ConfigurationBuilder();

            builder.AddUserSecrets <GetData>();
            IConfigurationRoot Configuration = builder.Build();
            var SelectedSecrets = Configuration.GetSection("COIReportDevinSecrets");

            token    = SelectedSecrets["OphthRealAPIToken"];
            reportID = SelectedSecrets["OphthRealDevinReportID"];
            apiURL   = SelectedSecrets["APIURL"];

            var redcap_api = new RedcapApi(apiURL);

            string[] metadataFields = { "clinicaldegree", "entity3", "state", "type3" };

            //This is all of the RedCapData, including the data dictionary!
            RedCapResult   = redcap_api.ExportReportsAsync(token, int.Parse(reportID), Redcap.Models.ReturnFormat.json).Result;
            MetaDataResult = redcap_api.ExportMetaDataAsync(token, Redcap.Models.ReturnFormat.csv, metadataFields).Result;
        }
        public void CanExportRepeatingInstrumentsAndEvents_ShouldReturn_string()
        {
            // Arrange
            var apiKey      = _token;
            var apiEndpoint = _uri;

            // Act

            /*
             * Using API Version 1.0.0+
             */
            var redcapApi = new RedcapApi(apiEndpoint);
            // executing method using default options
            var result = redcapApi.ExportRepeatingInstrumentsAndEvents(apiKey).Result;

            var data = JsonConvert.DeserializeObject(result).ToString();

            // Assert
            // Expecting multiple arms to be return since we asked for all arms by not providing any arms by passing null for the params
            Assert.Contains("event_name", data);
            Assert.Contains("form_name", data);
        }
Beispiel #7
0
 /// <summary>
 /// Method to send http request using MultipartFormDataContent
 /// Requests with attachments
 /// </summary>
 /// <param name="redcapApi"></param>
 /// <param name="payload">data</param>
 /// <param name="uri">URI of the api instance</param>
 /// <returns>string</returns>
 public static async Task <string> SendRequestAsync(this RedcapApi redcapApi, MultipartFormDataContent payload, Uri uri)
 {
     try
     {
         using (var client = new HttpClient())
         {
             using (var response = await client.PostAsync(uri, payload))
             {
                 if (response.IsSuccessStatusCode)
                 {
                     return(await response.Content.ReadAsStringAsync());
                 }
             }
         }
         return(Empty);
     }
     catch (Exception Ex)
     {
         Log.Error(Ex.Message);
         return(Empty);
     }
 }
        public void CanDeleteArmsAsync_SingleArm_ShouldReturn_number()
        {
            // Arrange
            var apiKey      = _token;
            var apiEndpoint = _uri;
            // arm 3 to be deleted
            var armarray = new string[]
            {
                "3"
            };

            // Act

            /*
             * Using API Version 1.0.0+
             */
            var redcapApi = new RedcapApi(apiEndpoint);
            var result    = redcapApi.DeleteArmsAsync(apiKey, "arm", "delete", armarray).Result;
            var data      = JsonConvert.DeserializeObject(result).ToString();

            // Assert
            // Expecting "1", the number of arms deleted, since we pass 1 arm to be deleted
            Assert.Contains("1", data);
        }
Beispiel #9
0
 /// <summary>
 /// Method obtains list of string from comma seperated strings
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="redcapApi"></param>
 /// <param name="arms"></param>
 /// <param name="delimiters"></param>
 /// <returns>List of string</returns>
 public static async Task <List <string> > ExtractArmsAsync <T>(this RedcapApi redcapApi, string arms, char[] delimiters)
 {
     if (!String.IsNullOrEmpty(arms))
     {
         try
         {
             var           _arms      = arms.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
             List <string> armsResult = new List <string>();
             foreach (var arm in _arms)
             {
                 armsResult.Add(arm);
             }
             return(await Task.FromResult(armsResult));
         }
         catch (Exception Ex)
         {
             Log.Error($"{Ex.Message}");
             return(await Task.FromResult(new List <string> {
             }));
         }
     }
     return(await Task.FromResult(new List <string> {
     }));
 }
Beispiel #10
0
 /// <summary>
 /// Method gets / extract records into list from string
 /// </summary>
 /// <param name="redcapApi"></param>
 /// <param name="records"></param>
 /// <param name="delimiters">char[] e.g [';',',']</param>
 /// <returns>List of string</returns>
 public static async Task <List <string> > ExtractRecordsAsync(this RedcapApi redcapApi, string records, char[] delimiters)
 {
     if (!String.IsNullOrEmpty(records))
     {
         try
         {
             var           recordItems   = records.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
             List <string> recordResults = new List <string>();
             foreach (var record in recordItems)
             {
                 recordResults.Add(record);
             }
             return(await Task.FromResult(recordResults));
         }
         catch (Exception Ex)
         {
             Log.Error($"{Ex.Message}");
             return(await Task.FromResult(new List <string> {
             }));
         }
     }
     return(await Task.FromResult(new List <string> {
     }));
 }
Beispiel #11
0
 /// <summary>
 /// This method converts int[] into a string. For example, given int[] of "[1,2,3]"
 /// gets converted to "["1","2","3"]"
 /// This is used as optional arguments for the Redcap Api
 /// </summary>
 /// <param name="redcapApi"></param>
 /// <param name="inputArray"></param>
 /// <returns>string</returns>
 public static async Task <string> ConvertIntArraytoString(this RedcapApi redcapApi, int[] inputArray)
 {
     try
     {
         StringBuilder builder = new StringBuilder();
         foreach (var v in inputArray)
         {
             builder.Append(v);
             // We do not need to append the , if less than or equal to a single string
             if (inputArray.Length <= 1)
             {
                 return(await Task.FromResult(builder.ToString()));
             }
             builder.Append(",");
         }
         // We trim the comma from the string for clarity
         return(await Task.FromResult(builder.ToString().TrimEnd(',')));
     }
     catch (Exception Ex)
     {
         Log.Error($"{Ex.Message}");
         return(await Task.FromResult(String.Empty));
     }
 }
Beispiel #12
0
 /// <summary>
 /// Method gets / extracts fields into list from string
 /// </summary>
 /// <param name="redcapApi"></param>
 /// <param name="fields"></param>
 /// <param name="delimiters">char[] e.g [';',',']</param>
 /// <returns>List of string</returns>
 public static async Task <List <string> > ExtractFieldsAsync(this RedcapApi redcapApi, string fields, char[] delimiters)
 {
     if (!String.IsNullOrEmpty(fields))
     {
         try
         {
             var           fieldItems   = fields.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
             List <string> fieldsResult = new List <string>();
             foreach (var field in fieldItems)
             {
                 fieldsResult.Add(field);
             }
             return(await Task.FromResult(fieldsResult));
         }
         catch (Exception Ex)
         {
             Log.Error($"{Ex.Message}");
             return(await Task.FromResult(new List <string> {
             }));
         }
     }
     return(await Task.FromResult(new List <string> {
     }));
 }
Beispiel #13
0
        static void Main(string[] args)
        {
            /*
             * This is a demo. This program provides a demonstration of potential calls using the API library.
             *
             * This program sequently runs through all the APIs methods.
             *
             * Directions:
             *
             * 1. Go into Redcap and create a new project with demographics.
             * 2. Turn on longitudinal and add two additional event. Event name should be "Event 1, Event 2, Event 3"
             *  Important, make sure you designate the instrument to atleast one event
             * 3. Create a folder in C: , name it redcap_download_files
             * 4. Create a text file in that folder, save it as test.txt
             * 5. Add a field, field type file upload to the project, name it "protocol_upload"
             * This allows the upload file method to upload files
             *
             */

            /*
             * Output to console
             */
            Console.WriteLine("Starting Redcap Api Demo..");
            Console.WriteLine("Please make sure you include a working redcap api token.");

            /*
             * Start a new instance of Redcap APi
             */
            //var redcapApi = new RedcapApi(_token, _uri);

            //Console.WriteLine("Calling API Methods < 1.0.0");

            //Console.WriteLine("Calling GetRecordAsync() . . .");
            //var GetRecordAsync = redcapApi.GetRecordAsync("1", ReturnFormat.json, RedcapDataType.flat, OnErrorFormat.json, null, null, null, null).Result;
            //var GetRecordAsyncData = JsonConvert.DeserializeObject(GetRecordAsync);
            //Console.WriteLine($"GetRecordAsync Result: {GetRecordAsyncData}");

            //Console.WriteLine("Calling ExportEventsAsync() . . .");
            //var exportEvents = redcapApi.ExportEventsAsync(ReturnFormat.json, OnErrorFormat.json).Result;
            //var exportEventsAsync = JsonConvert.DeserializeObject(exportEvents);
            //Console.WriteLine($"ExportEventsAsync Result: {exportEventsAsync}");

            //Console.WriteLine("Calling GetRecordsAsync() . . .");
            //var GetRecordsAsync = redcapApi.GetRecordsAsync(ReturnFormat.json, OnErrorFormat.json, RedcapDataType.flat).Result;
            //var GetRecordsAsyncData = JsonConvert.DeserializeObject(GetRecordsAsync);
            //Console.WriteLine($"GetRecordsAsync Result: {GetRecordsAsyncData}");

            //Console.WriteLine("Calling GetRedcapVersionAsync() . . .");
            //var GetRedcapVersionAsync = redcapApi.GetRedcapVersionAsync(ReturnFormat.json, RedcapDataType.flat).Result;
            //Console.WriteLine($"GetRedcapVersionAsync Result: {GetRedcapVersionAsync}");


            //var saveRecordsAsyncObject = new
            //{
            //    record_id = "1",
            //    redcap_event_name = "event_1_arm_1",
            //    first_name = "John",
            //    last_name = "Doe"
            //};

            //Console.WriteLine("Calling SaveRecordsAsync() . . .");
            //var SaveRecordsAsync = redcapApi.SaveRecordsAsync(saveRecordsAsyncObject, ReturnContent.ids, OverwriteBehavior.overwrite, ReturnFormat.json, RedcapDataType.flat, OnErrorFormat.json).Result;
            //var SaveRecordsAsyncData = JsonConvert.DeserializeObject(SaveRecordsAsync);
            //Console.WriteLine($"SaveRecordsAsync Result: {SaveRecordsAsyncData}");


            //Console.WriteLine("Calling ExportRecordsAsync() . . .");
            //var ExportRecordsAsync = redcapApi.ExportRecordsAsync(_token).Result;
            //var ExportRecordsAsyncData = JsonConvert.DeserializeObject(ExportRecordsAsync);
            //Console.WriteLine($"ExportRecordsAsync Result: {ExportRecordsAsyncData}");

            //Console.WriteLine("Calling ExportArmsAsync() . . .");
            //var ExportArmsAsync = redcapApi.ExportArmsAsync(ReturnFormat.json, OnErrorFormat.json).Result;
            //var ExportArmsAsyncData = JsonConvert.DeserializeObject(ExportArmsAsync);
            //Console.WriteLine($"ExportArmsAsync Result: {ExportArmsAsyncData}");

            //Console.WriteLine("Calling ExportRecordsAsync() . . .");
            //var ExportRecordsAsync2 = redcapApi.ExportRecordsAsync(_token, Content.Record).Result;
            //var ExportRecordsAsyncdata = JsonConvert.DeserializeObject(ExportRecordsAsync2);
            //Console.WriteLine($"ExportRecordsAsync Result: {ExportRecordsAsyncdata}");

            //var listOfEvents = new List<RedcapEvent>() {
            //    new RedcapEvent{arm_num = "1", custom_event_label = null, event_name = "Event 1", day_offset = "1", offset_min = "0", offset_max = "0", unique_event_name = "event_1_arm_1" }
            //};
            //Console.WriteLine("Calling ImportEventsAsync() . . .");
            //var ImportEventsAsync = redcapApi.ImportEventsAsync(listOfEvents, Override.False, ReturnFormat.json, OnErrorFormat.json).Result;
            //var ImportEventsAsyncData = JsonConvert.DeserializeObject(ImportEventsAsync);
            //Console.WriteLine($"ImportEventsAsync Result: {ImportEventsAsyncData}");

            //var pathImport = "C:\\redcap_download_files";
            //string importFileName = "test.txt";
            //var pathExport = "C:\\redcap_download_files";
            //var record = "1";
            var fieldName = "protocol_upload";
            var eventName = "event_1_arm_1";

            //var repeatingInstrument = "1";

            //Console.WriteLine("Calling ImportFile() . . .");
            //var ImportFile = redcapApi.ImportFileAsync(_uri, Content.File, RedcapAction.Import, record, fieldName, eventName, repeatingInstrument, importFileName, pathImport, OnErrorFormat.json).Result;
            //Console.WriteLine($"File has been imported! To verify, field history!");

            //Console.WriteLine("Calling ExportFile() . . .");
            //var ExportFile = redcapApi.ExportFileAsync(_uri, Content.File, RedcapAction.Import, record, fieldName, eventName, repeatingInstrument, OnErrorFormat.json, pathExport).Result;
            //Console.WriteLine($"ExportFile Result: {ExportFile} to : {pathExport}");

            //Console.WriteLine("Calling DeleteFile() . . .");
            //var DeleteFile = redcapApi.DeleteFileAsync("1", "protocol_upload", "event_1_arm_1", "", OnErrorFormat.json).Result;
            //Console.WriteLine($"File has been deleted! To verify, field history!");

            //Console.WriteLine("Calls to < 1.0.0 completed...");
            //// Make a sound!
            //Console.Beep();



            Console.WriteLine("-----------------------------Starting API Version 1.0.5+-------------");
            Console.WriteLine("Starting demo for API Version 1.0.0+");
            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            Console.WriteLine("Creating a new instance of RedcapApi");
            var redcap_api_1_0_7 = new RedcapApi(_uri);

            Console.WriteLine($"Using {_uri} for redcap api endpoint.");

            #region ImportRecordsAsync()
            Console.WriteLine("Calling ImportRecordsAsync() . . .");

            /*
             * Create a list of object of type instrument or fields. Add its properties then add it to the list.
             * record_id is required
             */
            var data = new List <Demographic> {
                new Demographic {
                    FirstName = "Jon", LastName = "Doe", RecordId = "1"
                }
            };
            Console.WriteLine($"Importing record {string.Join(",", data.Select(x=>x.RecordId).ToList())} . . .");
            var ImportRecordsAsync     = redcap_api_1_0_7.ImportRecordsAsync(_token, Content.Record, ReturnFormat.json, RedcapDataType.flat, OverwriteBehavior.normal, false, data, "MDY", ReturnContent.count, OnErrorFormat.json).Result;
            var ImportRecordsAsyncData = JsonConvert.DeserializeObject(ImportRecordsAsync);
            Console.WriteLine($"ImportRecordsAsync Result: {ImportRecordsAsyncData}");
            #endregion ImportRecordsAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region DeleteRecordsAsync()
            Console.WriteLine("Calling DeleteRecordsAsync() . . .");
            var records = new string[] { "1" };
            Console.WriteLine($"Deleting record {string.Join(",", records)} . . .");
            var DeleteRecordsAsync = redcap_api_1_0_7.DeleteRecordsAsync(_token, Content.Record, RedcapAction.Delete, records, 1).Result;

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            Console.WriteLine($"DeleteRecordsAsync Result: {DeleteRecordsAsync}");
            #endregion DeleteRecordsAsync()

            #region ExportArmsAsync()
            var arms = new string[] {};
            Console.WriteLine("Calling ExportArmsAsync()");
            var ExportArmsAsyncResult = redcap_api_1_0_7.ExportArmsAsync(_token, Content.Arm, ReturnFormat.json, arms, OnErrorFormat.json).Result;
            Console.WriteLine($"ExportArmsAsyncResult: {ExportArmsAsyncResult}");
            #endregion ExportArmsAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ImportArmsAsync()
            var ImportArmsAsyncData = new List <RedcapArm> {
                new RedcapArm {
                    ArmNumber = "1", Name = "hooo"
                }, new RedcapArm {
                    ArmNumber = "2", Name = "heee"
                }, new RedcapArm {
                    ArmNumber = "3", Name = "hawww"
                }
            };
            Console.WriteLine("Calling ImportArmsAsync()");
            var ImportArmsAsyncResult = redcap_api_1_0_7.ImportArmsAsync(_token, Content.Arm, Override.False, RedcapAction.Import, ReturnFormat.json, ImportArmsAsyncData, OnErrorFormat.json).Result;
            Console.WriteLine($"ImportArmsAsyncResult: {ImportArmsAsyncResult}");
            #endregion ImportArmsAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region DeleteArmsAsync()
            var DeleteArmsAsyncData = new string[] { "3" };
            Console.WriteLine("Calling DeleteArmsAsync()");
            var DeleteArmsAsyncResult = redcap_api_1_0_7.DeleteArmsAsync(_token, Content.Arm, RedcapAction.Delete, DeleteArmsAsyncData).Result;
            Console.WriteLine($"DeleteArmsAsyncResult: {DeleteArmsAsyncResult}");
            #endregion DeleteArmsAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ExportEventsAsync()
            var ExportEventsAsyncData = new string[] { "1" };
            Console.WriteLine("Calling ExportEventsAsync()");
            var ExportEventsAsyncResult = redcap_api_1_0_7.ExportEventsAsync(_token, Content.Event, ReturnFormat.json, ExportEventsAsyncData, OnErrorFormat.json).Result;
            Console.WriteLine($"ExportEventsAsyncResult: {ExportEventsAsyncResult}");
            #endregion ExportEventsAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ImportEventsAsync()
            Console.WriteLine("Calling ExportEventsAsync()");
            var eventList = new List <RedcapEvent> {
                new RedcapEvent {
                    EventName        = "baseline",
                    ArmNumber        = "1",
                    DayOffset        = "1",
                    MinimumOffset    = "0",
                    MaximumOffset    = "0",
                    UniqueEventName  = "baseline_arm_1",
                    CustomEventLabel = "hello baseline"
                },
                new RedcapEvent {
                    EventName        = "clinical",
                    ArmNumber        = "1",
                    DayOffset        = "1",
                    MinimumOffset    = "0",
                    MaximumOffset    = "0",
                    UniqueEventName  = "clinical_arm_1",
                    CustomEventLabel = "hello clinical"
                }
            };
            var ImportEventsAsyncResult = redcap_api_1_0_7.ImportEventsAsync(_token, Content.Event, RedcapAction.Import, Override.False, ReturnFormat.json, eventList, OnErrorFormat.json).Result;
            Console.WriteLine($"ImportEventsAsyncResult: {ImportEventsAsyncResult}");
            #endregion ImportEventsAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();


            #region DeleteEventsAsync()
            var DeleteEventsAsyncData = new string[] { "baseline_arm_1" };
            Console.WriteLine("Calling DeleteEventsAsync()");
            var DeleteEventsAsyncResult = redcap_api_1_0_7.DeleteEventsAsync(_token, Content.Event, RedcapAction.Delete, DeleteEventsAsyncData).Result;
            Console.WriteLine($"DeleteEventsAsyncResult: {DeleteEventsAsyncResult}");
            #endregion DeleteEventsAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();


            #region ExportFieldNamesAsync()
            Console.WriteLine("Calling ExportFieldNamesAsync(), first_name");
            var ExportFieldNamesAsyncResult = redcap_api_1_0_7.ExportFieldNamesAsync(_token, Content.ExportFieldNames, ReturnFormat.json, "first_name", OnErrorFormat.json).Result;
            Console.WriteLine($"ExportFieldNamesAsyncResult: {ExportFieldNamesAsyncResult}");
            #endregion ExportFieldNamesAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();


            #region ImportFileAsync()
            var recordId       = "1";
            var fileName       = "test.txt";
            var fileUploadPath = @"C:\redcap_upload_files";
            Console.WriteLine($"Calling ImportFileAsync(), {fileName}");
            var ImportFileAsyncResult = redcap_api_1_0_7.ImportFileAsync(_token, Content.File, RedcapAction.Import, recordId, fieldName, eventName, null, fileName, fileUploadPath, OnErrorFormat.json).Result;
            Console.WriteLine($"ImportFileAsyncResult: {ImportFileAsyncResult}");
            #endregion ImportFileAsync()


            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ExportFileAsync()
            Console.WriteLine($"Calling ExportFileAsync(), {fileName} for field name {fieldName}, not save the file.");
            var ExportFileAsyncResult = redcap_api_1_0_7.ExportFileAsync(_token, Content.File, RedcapAction.Export, recordId, fieldName, eventName, null, OnErrorFormat.json).Result;
            Console.WriteLine($"ExportFileAsyncResult: {ExportFileAsyncResult}");
            #endregion ExportFileAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ExportFileAsync()
            var filedDownloadPath = @"C:\redcap_download_files";
            Console.WriteLine($"Calling ExportFileAsync(), {fileName} for field name {fieldName}, saving the file.");
            var ExportFileAsyncResult2 = redcap_api_1_0_7.ExportFileAsync(_token, Content.File, RedcapAction.Export, recordId, fieldName, eventName, null, OnErrorFormat.json, filedDownloadPath).Result;
            Console.WriteLine($"ExportFileAsyncResult2: {ExportFileAsyncResult2}");
            #endregion ExportFileAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region DeleteFileAsync()
            Console.WriteLine($"Calling DeleteFileAsync(), deleting file: {fileName} for field: {fieldName}");
            var DeleteFileAsyncResult = redcap_api_1_0_7.DeleteFileAsync(_token, Content.File, RedcapAction.Delete, recordId, fieldName, eventName, "1", OnErrorFormat.json).Result;
            Console.WriteLine($"DeleteFileAsyncResult: {DeleteFileAsyncResult}");
            #endregion DeleteFileAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ExportInstrumentsAsync()
            Console.WriteLine($"Calling DeleteFileAsync()");
            var ExportInstrumentsAsyncResult = redcap_api_1_0_7.ExportInstrumentsAsync(_token, Content.Instrument, ReturnFormat.json).Result;
            Console.WriteLine($"ExportInstrumentsAsyncResult: {ExportInstrumentsAsyncResult}");
            #endregion ExportInstrumentsAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ExportPDFInstrumentsAsync()
            Console.WriteLine($"Calling ExportPDFInstrumentsAsync(), returns raw");
            var ExportPDFInstrumentsAsyncResult = redcap_api_1_0_7.ExportPDFInstrumentsAsync(_token, Content.Pdf, recordId, eventName, "demographics", true, OnErrorFormat.json).Result;
            Console.WriteLine($"ExportInstrumentsAsyncResult: {JsonConvert.SerializeObject(ExportPDFInstrumentsAsyncResult)}");
            #endregion ExportPDFInstrumentsAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ExportPDFInstrumentsAsync()
            Console.WriteLine($"Calling ExportPDFInstrumentsAsync(), saving pdf file to {filedDownloadPath}");
            var ExportPDFInstrumentsAsyncResult2 = redcap_api_1_0_7.ExportPDFInstrumentsAsync(_token, recordId, eventName, "demographics", true, filedDownloadPath, OnErrorFormat.json).Result;
            Console.WriteLine($"ExportPDFInstrumentsAsyncResult2: {ExportPDFInstrumentsAsyncResult2}");
            #endregion ExportPDFInstrumentsAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ExportInstrumentMappingAsync()
            Console.WriteLine($"Calling ExportInstrumentMappingAsync()");
            var ExportInstrumentMappingAsyncResult = redcap_api_1_0_7.ExportInstrumentMappingAsync(_token, Content.FormEventMapping, ReturnFormat.json, arms, OnErrorFormat.json).Result;
            Console.WriteLine($"ExportInstrumentMappingAsyncResult: {ExportInstrumentMappingAsyncResult}");
            #endregion ExportInstrumentMappingAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ImportInstrumentMappingAsync()
            var importInstrumentMappingData = new List <FormEventMapping> {
                new FormEventMapping {
                    arm_num = "1", unique_event_name = "clinical_arm_1", form = "demographics"
                }
            };
            Console.WriteLine($"Calling ImportInstrumentMappingAsync()");
            var ImportInstrumentMappingAsyncResult = redcap_api_1_0_7.ImportInstrumentMappingAsync(_token, Content.FormEventMapping, ReturnFormat.json, importInstrumentMappingData, OnErrorFormat.json).Result;
            Console.WriteLine($"ImportInstrumentMappingAsyncResult: {ImportInstrumentMappingAsyncResult}");
            #endregion ImportInstrumentMappingAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ExportMetaDataAsync()
            Console.WriteLine($"Calling ExportMetaDataAsync()");
            var ExportMetaDataAsyncResult = redcap_api_1_0_7.ExportMetaDataAsync(_token, Content.MetaData, ReturnFormat.json, null, null, OnErrorFormat.json).Result;
            Console.WriteLine($"ExportMetaDataAsyncResult: {ExportMetaDataAsyncResult}");
            #endregion ExportMetaDataAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ImportMetaDataAsync()

            /*
             * This imports 1 field into the data dictionary
             */
            var importMetaData = new List <RedcapMetaData> {
                new RedcapMetaData {
                    field_name = "first_name", form_name = "demographics", field_type = "text", field_label = "First Name"
                }
            };
            Console.WriteLine($"Not calling ImportMetaDataAsync(), still change data dictionary to include 1 field");
            //var ImportMetaDataAsyncResult = redcap_api_1_0_7.ImportMetaDataAsync(_token, "metadata", ReturnFormat.json, importMetaData, OnErrorFormat.json).Result;
            //Console.WriteLine($"ImportMetaDataAsyncResult: {ImportMetaDataAsyncResult}");
            #endregion ImportMetaDataAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region CreateProjectAsync()
            var projectData = new List <RedcapProject> {
                new RedcapProject {
                    project_title = "Amazing Project ", purpose = ProjectPurpose.Other, purpose_other = "Test"
                }
            };
            Console.WriteLine($"Calling CreateProjectAsync(), creating a new project with Amazing Project as title, purpose 1 (other) ");
            Console.WriteLine($"-----------------------Notice the use of SUPER TOKEN------------------------");
            var CreateProjectAsyncResult = redcap_api_1_0_7.CreateProjectAsync(_superToken, Content.Project, ReturnFormat.json, projectData, OnErrorFormat.json, null).Result;
            Console.WriteLine($"CreateProjectAsyncResult: {CreateProjectAsyncResult}");
            #endregion CreateProjectAsync()
            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ImportProjectInfoAsync()
            var projectInfo = new RedcapProjectInfo {
                ProjectTitle = "Updated Amazing Project ", Purpose = ProjectPurpose.QualityImprovement, SurveysEnabled = 1
            };
            Console.WriteLine($"Calling ImportProjectInfoAsync()");
            var ImportProjectInfoAsyncResult = redcap_api_1_0_7.ImportProjectInfoAsync(_token, Content.ProjectSettings, ReturnFormat.json, projectInfo).Result;
            Console.WriteLine($"ImportProjectInfoAsyncResult: {ImportProjectInfoAsyncResult}");
            #endregion ImportProjectInfoAsync()
            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ExportProjectInfoAsync()
            Console.WriteLine($"Calling ExportProjectInfoAsync()");
            var ExportProjectInfoAsyncResult = redcap_api_1_0_7.ExportProjectInfoAsync(_token, Content.ProjectSettings, ReturnFormat.json).Result;
            Console.WriteLine($"ExportProjectInfoAsyncResult: {ExportProjectInfoAsyncResult}");
            #endregion ExportProjectInfoAsync()

            Console.WriteLine("----------------------------Demo completed! Press Enter to Exit-------------");
            Console.ReadLine();
        }
Beispiel #14
0
        /// <summary>
        /// Sends request using http
        /// </summary>
        /// <param name="redcapApi"></param>
        /// <param name="payload">data</param>
        /// <param name="uri">URI of the api instance</param>
        /// <param name="isLargeDataset">Requests size > 32k chars </param>
        /// <returns></returns>
        public static async Task <string> SendRequestAsync(this RedcapApi redcapApi, Dictionary <string, string> payload, Uri uri, bool isLargeDataset = false)
        {
            try
            {
                string _responseMessage = Empty;

                using (var client = new HttpClient())
                {
                    // extract the filepath
                    var pathValue = payload.Where(x => x.Key == "filePath").FirstOrDefault().Value;
                    var pathkey   = payload.Where(x => x.Key == "filePath").FirstOrDefault().Key;

                    if (!string.IsNullOrEmpty(pathkey))
                    {
                        // the actual payload does not contain a 'filePath' key
                        payload.Remove(pathkey);
                    }

                    /*
                     * Encode the values for payload
                     * Add in ability to process large data set, using StringContent
                     * Thanks to Ibrahim for pointing this out.
                     * https://stackoverflow.com/questions/23703735/how-to-set-large-string-inside-httpcontent-when-using-httpclient/23740338
                     */
                    if (isLargeDataset)
                    {
                        /*
                         * Send request with large data set
                         */

                        var serializedPayload = JsonConvert.SerializeObject(payload);
                        using (var content = new StringContent(serializedPayload, Encoding.UTF8, "application/json"))
                        {
                            using (var response = await client.PostAsync(uri, content))
                            {
                                if (response.IsSuccessStatusCode)
                                {
                                    // Get the filename so we can save with the name
                                    var headers  = response.Content.Headers;
                                    var fileName = headers.ContentType.Parameters.Select(x => x.Value).FirstOrDefault();
                                    if (!string.IsNullOrEmpty(fileName))
                                    {
                                        var contentDisposition = response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                                        {
                                            FileName = fileName
                                        };
                                    }

                                    if (!string.IsNullOrEmpty(pathValue))
                                    {
                                        // save the file to a specified location using an extension method
                                        await response.Content.ReadAsFileAsync(fileName, pathValue, true);

                                        _responseMessage = fileName;
                                    }
                                    else
                                    {
                                        _responseMessage = await response.Content.ReadAsStringAsync();
                                    }
                                }
                                else
                                {
                                    _responseMessage = await response.Content.ReadAsStringAsync();
                                }
                            }
                        }
                        return(_responseMessage);
                    }
                    else
                    {
                        /*
                         * Maximum character limit of 32,000 using FormUrlEncodedContent
                         * Send request using small data set
                         */
                        using (var content = new FormUrlEncodedContent(payload))
                        {
                            using (var response = await client.PostAsync(uri, content))
                            {
                                if (response.IsSuccessStatusCode)
                                {
                                    // Get the filename so we can save with the name
                                    var headers  = response.Content.Headers;
                                    var fileName = headers.ContentType.Parameters.Select(x => x.Value).FirstOrDefault();
                                    if (!string.IsNullOrEmpty(fileName))
                                    {
                                        var contentDisposition = response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                                        {
                                            FileName = fileName
                                        };
                                    }


                                    if (!string.IsNullOrEmpty(pathValue))
                                    {
                                        var fileExtension = payload.Where(x => x.Key == "content" && x.Value == "pdf").SingleOrDefault().Value;
                                        if (!string.IsNullOrEmpty(fileExtension))
                                        {
                                            // pdf
                                            fileName = payload.Where(x => x.Key == "instrument").SingleOrDefault().Value;
                                            // to do , make extensions for various types
                                            // save the file to a specified location using an extension method
                                            await response.Content.ReadAsFileAsync(fileName, pathValue, true, fileExtension);
                                        }
                                        else
                                        {
                                            await response.Content.ReadAsFileAsync(fileName, pathValue, true, fileExtension);
                                        }
                                        _responseMessage = fileName;
                                    }
                                    else
                                    {
                                        _responseMessage = await response.Content.ReadAsStringAsync();
                                    }
                                }
                                else
                                {
                                    _responseMessage = await response.Content.ReadAsStringAsync();
                                }
                            }
                        }
                    }
                    return(_responseMessage);
                }
            }
            catch (Exception Ex)
            {
                Log.Error($"{Ex.Message}");
                return(Empty);
            }
        }
        public async Task <DataTable> GetDataTableAsync(string collectionName)
        {
            DataTable dataTable              = new DataTable("Table1");
            var       red_cap_api            = new RedcapApi(redcapuri);
            var       ExportRecordsAsync     = red_cap_api.ExportRecordsAsync(redcapapikey, Content.Record).Result;
            var       ExportRecordsAsyncData = JsonConvert.DeserializeObject(ExportRecordsAsync);

            dataTable    = JsonConvert.DeserializeObject <System.Data.DataTable>(ExportRecordsAsyncData.ToString());
            numberOfRows = dataTable.Rows.Count;
            var       ExportMetaDataAsync     = red_cap_api.ExportMetaDataAsync(redcapapikey, Content.MetaData, ReturnFormat.json, null, null, OnErrorFormat.json).Result;
            var       ExportMetaDataAsyncData = JsonConvert.DeserializeObject(ExportMetaDataAsync);
            DataTable metaDataTable           =
                JsonConvert.DeserializeObject <System.Data.DataTable>(ExportMetaDataAsyncData.ToString());
            int           typeInt            = metaDataTable.Columns.IndexOf("field_type");
            int           validationInt      = metaDataTable.Columns.IndexOf("text_validation_type_or_show_slider_number");
            DataTable     dataTableCloned    = dataTable.Clone();
            bool          cloneAgain         = false;
            List <string> booleanDataColumns = new List <string>();

            foreach (DataColumn dc in dataTableCloned.Columns)
            {
                string    columnName = dc.ColumnName;
                string    select     = "field_name = '" + dc.ColumnName + "'";
                DataRow[] selected   = metaDataTable.Select(select);
                if (selected.Length > 0)
                {
                    DataRow selected0  = selected[0];
                    string  type       = (string)selected0[typeInt];
                    string  validation = (string)selected0[validationInt];
                    if (type.Equals("calc") || validation.Equals("number"))
                    {
                        dc.DataType = typeof(double);
                    }
                    else if (validation.Equals("integer"))
                    {
                        dc.DataType = typeof(Int32);
                    }
                    else if (validation.Contains("date"))
                    {
                        dc.DataType = typeof(System.DateTime);
                    }
                }
                else if (dc.ColumnName.IndexOf("__") >= 0)
                {
                    select   = "field_name = '" + dc.ColumnName.Substring(0, dc.ColumnName.IndexOf("__")) + "'";
                    selected = metaDataTable.Select(select);
                    if (selected.Length > 0)
                    {
                        dc.DataType = typeof(System.Byte);
                        cloneAgain  = true;
                        booleanDataColumns.Add(dc.ColumnName);
                    }
                }
            }
            foreach (DataRow dr in dataTable.Rows)
            {
                for (int i = 0; i < dataTable.Columns.Count; i++)
                {
                    if (String.IsNullOrEmpty((string)dr[i]))
                    {
                        dr[i] = null;
                    }
                }
                dataTableCloned.ImportRow(dr);
            }
            if (cloneAgain)
            {
                DataTable dataTableClonedCloned = dataTableCloned.Clone();
                foreach (DataColumn dc in dataTableClonedCloned.Columns)
                {
                    if (booleanDataColumns.Contains(dc.ColumnName))
                    {
                        dc.DataType = typeof(System.Boolean);
                    }
                }
                foreach (DataRow dr in dataTableCloned.Rows)
                {
                    dataTableClonedCloned.ImportRow(dr);
                }
                return(dataTableClonedCloned);
            }
            return(dataTableCloned);

            if (expired)
            {
                return(dataTable);
            }

            string surveyId = collectionName.Substring(collectionName.IndexOf("{{") + 2, 36);

            using (SqlConnection connection = new SqlConnection(certInfo.ConnectionString))
            {
                await connection.OpenAsync();

                string commandString = "select ResponseJson from SurveyResponse where ResponseJson is not null and surveyid = '" + surveyId + "'";
                using (SqlCommand command = new SqlCommand(commandString, connection))
                {
                    using (SqlDataReader reader = await command.ExecuteReaderAsync())
                    {
                        while (await reader.ReadAsync())
                        {
                            string json = reader.GetFieldValue <string>(0);
                            dataTable = GetDataTableFromJson(dataTable, json);
                        }
                    }
                }
            }
            return(dataTable);
        }
Beispiel #16
0
        /// <summary>
        /// This method extracts and converts an object's properties and associated values to redcap type and values.
        /// </summary>
        /// <param name="redcapApi"></param>
        /// <param name="input">Object</param>
        /// <returns>Dictionary of key value pair.</returns>
        public static async Task <Dictionary <string, string> > GetProperties(this RedcapApi redcapApi, object input)
        {
            try
            {
                if (input != null)
                {
                    // Get the type
                    var type = input.GetType();
                    var obj  = new Dictionary <string, string>();
                    // Get the properties
                    var            props      = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
                    PropertyInfo[] properties = input.GetType().GetProperties();
                    foreach (var prop in properties)
                    {
                        // get type of column
                        // The the type of the property
                        Type columnType = prop.PropertyType;

                        // We need to set lower case for REDCap's variable nameing convention (lower casing)
                        string propName = prop.Name.ToLower();
                        // We check for null values
                        var propValue = type.GetProperty(prop.Name).GetValue(input, null)?.ToString();
                        if (propValue != null)
                        {
                            var t = columnType.GetGenericArguments();
                            if (t.Length > 0)
                            {
                                if (columnType.GenericTypeArguments[0].FullName == "System.DateTime")
                                {
                                    var dt = DateTime.Parse(propValue);
                                    propValue = dt.ToString();
                                }
                                if (columnType.GenericTypeArguments[0].FullName == "System.Boolean")
                                {
                                    if (propValue == "True")
                                    {
                                        propValue = "1";
                                    }
                                    else
                                    {
                                        propValue = "0";
                                    }
                                }
                            }
                            obj.Add(propName, propValue);
                        }
                        else
                        {
                            // We have to make sure we handle for null values.
                            obj.Add(propName, null);
                        }
                    }
                    return(await Task.FromResult(obj));
                }
                return(await Task.FromResult(new Dictionary <string, string> {
                }));
            }
            catch (Exception Ex)
            {
                Log.Error($"{Ex.Message}");
                return(await Task.FromResult(new Dictionary <string, string> {
                }));
            }
        }
Beispiel #17
0
        /// <summary>
        /// Tuple that returns both inputFormat and redcap returnFormat
        /// </summary>
        /// <param name="redcapApi"></param>
        /// <param name="format">csv, json[default], xml , odm ('odm' refers to CDISC ODM XML format, specifically ODM version 1.3.1)</param>
        /// <param name="onErrorFormat"></param>
        /// <param name="redcapDataType"></param>
        /// <returns>tuple, string, string, string</returns>
        public static async Task <(string format, string onErrorFormat, string redcapDataType)> HandleFormat(this RedcapApi redcapApi, ReturnFormat?format = ReturnFormat.json, OnErrorFormat?onErrorFormat = OnErrorFormat.json, RedcapDataType?redcapDataType = RedcapDataType.flat)
        {
            // default
            var _format         = ReturnFormat.json.ToString();
            var _onErrorFormat  = OnErrorFormat.json.ToString();
            var _redcapDataType = RedcapDataType.flat.ToString();

            try
            {
                switch (format)
                {
                case ReturnFormat.json:
                    _format = ReturnFormat.json.ToString();
                    break;

                case ReturnFormat.csv:
                    _format = ReturnFormat.csv.ToString();
                    break;

                case ReturnFormat.xml:
                    _format = ReturnFormat.xml.ToString();
                    break;

                default:
                    _format = ReturnFormat.json.ToString();
                    break;
                }

                switch (onErrorFormat)
                {
                case OnErrorFormat.json:
                    _onErrorFormat = OnErrorFormat.json.ToString();
                    break;

                case OnErrorFormat.csv:
                    _onErrorFormat = OnErrorFormat.csv.ToString();
                    break;

                case OnErrorFormat.xml:
                    _onErrorFormat = OnErrorFormat.xml.ToString();
                    break;

                default:
                    _onErrorFormat = OnErrorFormat.json.ToString();
                    break;
                }

                switch (redcapDataType)
                {
                case RedcapDataType.flat:
                    _redcapDataType = RedcapDataType.flat.ToString();
                    break;

                case RedcapDataType.eav:
                    _redcapDataType = RedcapDataType.eav.ToString();
                    break;

                case RedcapDataType.longitudinal:
                    _redcapDataType = RedcapDataType.longitudinal.ToString();
                    break;

                case RedcapDataType.nonlongitudinal:
                    _redcapDataType = RedcapDataType.nonlongitudinal.ToString();
                    break;

                default:
                    _redcapDataType = RedcapDataType.flat.ToString();
                    break;
                }

                return(await Task.FromResult((_format, _onErrorFormat, _redcapDataType)));
            }
            catch (Exception Ex)
            {
                Log.Error(Ex.Message);
                return(await Task.FromResult((_format, _onErrorFormat, _redcapDataType)));
            }
        }
 public RedcapApiTests()
 {
     _redcapApi = new RedcapApi(_uri);
 }
Beispiel #19
0
        /// <summary>
        /// Sends request using http
        /// </summary>
        /// <param name="redcapApi"></param>
        /// <param name="payload">data</param>
        /// <param name="uri">URI of the api instance</param>
        /// <returns></returns>
        public static async Task <string> SendPostRequestAsync(this RedcapApi redcapApi, Dictionary <string, string> payload, Uri uri)
        {
            try
            {
                string _responseMessage = Empty;

                using (var handler = GetHttpHandler())
                    using (var client = new HttpClient(handler))
                    {
                        // extract the filepath
                        var pathValue = payload.Where(x => x.Key == "filePath").FirstOrDefault().Value;
                        var pathkey   = payload.Where(x => x.Key == "filePath").FirstOrDefault().Key;

                        if (!string.IsNullOrEmpty(pathkey))
                        {
                            // the actual payload does not contain a 'filePath' key
                            payload.Remove(pathkey);
                        }

                        using (var content = new CustomFormUrlEncodedContent(payload))
                        {
                            using (var response = await client.PostAsync(uri, content))
                            {
                                if (response.IsSuccessStatusCode)
                                {
                                    // Get the filename so we can save with the name
                                    var headers  = response.Content.Headers;
                                    var fileName = headers.ContentType?.Parameters.Select(x => x.Value).FirstOrDefault();
                                    if (!string.IsNullOrEmpty(fileName))
                                    {
                                        var contentDisposition = response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                                        {
                                            FileName = fileName
                                        };
                                    }


                                    if (!string.IsNullOrEmpty(pathValue))
                                    {
                                        var fileExtension = payload.Where(x => x.Key == "content" && x.Value == "pdf").SingleOrDefault().Value;
                                        if (!string.IsNullOrEmpty(fileExtension))
                                        {
                                            // pdf
                                            fileName = payload.Where(x => x.Key == "instrument").SingleOrDefault().Value;
                                            // to do , make extensions for various types
                                            // save the file to a specified location using an extension method
                                            await response.Content.ReadAsFileAsync(fileName, pathValue, true, fileExtension);
                                        }
                                        else
                                        {
                                            await response.Content.ReadAsFileAsync(fileName, pathValue, true, fileExtension);
                                        }
                                        _responseMessage = fileName;
                                    }
                                    else
                                    {
                                        _responseMessage = await response.Content.ReadAsStringAsync();
                                    }
                                }
                                else
                                {
                                    _responseMessage = await response.Content.ReadAsStringAsync();
                                }
                            }
                        }
                        return(_responseMessage);
                    }
            }
            catch (Exception Ex)
            {
                Log.Error($"{Ex.Message}");
                return(Empty);
            }
        }
Beispiel #20
0
        static void InitializeDemo()
        {
            /*
             * Change this token for your demo project
             * Using one created from a local dev instance
             */
            string _token = string.Empty;

            /*
             * Change this token for your demo project
             * Using one created from a local dev instance
             */
            string _superToken = "2E59CA118ABC17D393722524C501CF0BAC51689746E24BFDAF47B38798BD827A";

            /*
             * Using a local redcap development instsance
             */
            string _uri      = string.Empty;
            var    fieldName = "file_upload";
            var    eventName = "event_1_arm_1";

            /*
             * Output to console
             */
            Console.WriteLine("Starting Redcap Api Demo..");
            Console.WriteLine("Please make sure you include a working redcap api token.");
            Console.WriteLine("Enter your redcap instance uri, example: http://localhost/redcap");
            _uri = Console.ReadLine();
            if (string.IsNullOrEmpty(_uri))
            {
                // provide a default one here..
                _uri = "http://localhost/redcap";
            }
            _uri = _uri + "/api/";
            Console.WriteLine("Enter your api token for the project to test: ");
            var token = Console.ReadLine();

            if (string.IsNullOrEmpty(token))
            {
                _token = "DF70F2EC94AE05021F66423B386095BD";
            }
            else
            {
                _token = token;
            }
            Console.WriteLine($"Using Endpoint=> {_uri} Token => {_token}");

            Console.WriteLine("-----------------------------Starting API Version 1.0.5+-------------");
            Console.WriteLine("Starting demo for API Version 1.0.0+");
            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            Console.WriteLine("Creating a new instance of RedcapApi");
            var redcap_api_1_1_0 = new RedcapApi(_uri);

            Console.WriteLine($"Using {_uri.ToString()} for redcap api endpoint.");

            #region ExportLoggingAsync()
            Console.WriteLine("Calling ExportLoggingAsync() . . .");
            Console.WriteLine($"Exporting logs for User . . .");
            var ExportLoggingAsync = redcap_api_1_1_0.ExportLoggingAsync(_token, Content.Log, ReturnFormat.json, LogType.User).Result;
            Console.WriteLine($"ExportLoggingAsync Results: {JsonConvert.DeserializeObject(ExportLoggingAsync)}");
            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #endregion

            #region ImportDagsAsync()
            Console.WriteLine("Calling ImportDagsAsync() . . .");
            Console.WriteLine($"Importing Dags . . .");
            var dags = CreateDags(5);
            var ImportDagsAsyncResult = redcap_api_1_1_0.ImportDagsAsync(_token, Content.Dag, RedcapAction.Import, ReturnFormat.json, dags).Result;
            Console.WriteLine($"ImportDagsAsync Results: {JsonConvert.DeserializeObject(ImportDagsAsyncResult)}");
            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #endregion

            #region ExportDagsAsync()
            Console.WriteLine("Calling ExportDagsAsync() . . .");
            Console.WriteLine($"Exporting Dags . . .");
            var ExportDagsAsyncResult = redcap_api_1_1_0.ExportDagsAsync(_token, Content.Dag, ReturnFormat.json).Result;
            Console.WriteLine($"ExportDagsAsync Results: {JsonConvert.DeserializeObject(ExportDagsAsyncResult)}");
            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();
            #endregion

            #region DeleteDagsAsync()
            Console.WriteLine("Calling DeleteDagsAsync() . . .");
            Console.WriteLine($"Deleting Dags . . .");
            var dagsToDelete          = JsonConvert.DeserializeObject <List <RedcapDag> >(ExportDagsAsyncResult).Select(x => x.UniqueGroupName).ToArray();
            var DeleteDagsAsyncResult = redcap_api_1_1_0.DeleteDagsAsync(_token, Content.Dag, RedcapAction.Delete, dagsToDelete).Result;
            Console.WriteLine($"DeleteDagsAsync Results: {JsonConvert.DeserializeObject(DeleteDagsAsyncResult)}");
            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();
            #endregion

            #region ImportRecordsAsync()
            Console.WriteLine("Calling ImportRecordsAsync() . . .");
            // get demographics data
            var importDemographicsData = CreateDemographics(includeBio: true, 5);
            Console.WriteLine("Serializing the data . . .");
            Console.WriteLine($"Importing record {string.Join(",", importDemographicsData.Select(x => x.RecordId).ToList())} . . .");
            var ImportRecordsAsync     = redcap_api_1_1_0.ImportRecordsAsync(_token, Content.Record, ReturnFormat.json, RedcapDataType.flat, OverwriteBehavior.normal, false, importDemographicsData, "MDY", CsvDelimiter.tab, ReturnContent.count, OnErrorFormat.json).Result;
            var ImportRecordsAsyncData = JsonConvert.DeserializeObject(ImportRecordsAsync);
            Console.WriteLine($"ImportRecordsAsync Result: {ImportRecordsAsyncData}");
            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();
            #endregion ImportRecordsAsync()

            #region ExportRecordsAsync()
            Console.WriteLine($"Calling ExportRecordsAsync()");
            Console.WriteLine($"Using records from the imported method..");
            var recordsToExport          = importDemographicsData.Select(x => x.RecordId).ToArray();
            var instrumentName           = new string[] { "demographics" };
            var ExportRecordsAsyncResult = redcap_api_1_1_0.ExportRecordsAsync(_token, Content.Record, ReturnFormat.json, RedcapDataType.flat, recordsToExport, null, instrumentName).Result;
            Console.WriteLine($"ExportRecordsAsyncResult: {ExportRecordsAsyncResult}");
            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();
            #endregion ExportRecordsAsync()

            #region DeleteRecordsAsync()
            Console.WriteLine("Calling DeleteRecordsAsync() . . .");
            var records = importDemographicsData.Select(x => x.RecordId).ToArray();
            Console.WriteLine($"Deleting record {string.Join(",", recordsToExport)} . . .");
            var DeleteRecordsAsync     = redcap_api_1_1_0.DeleteRecordsAsync(_token, Content.Record, RedcapAction.Delete, recordsToExport, 1).Result;
            var DeleteRecordsAsyncData = JsonConvert.DeserializeObject(DeleteRecordsAsync);
            Console.WriteLine($"DeleteRecordsAsync Result: {DeleteRecordsAsyncData}");

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();
            #endregion DeleteRecordsAsync()


            #region ExportArmsAsync()
            var arms = new string[] { };
            Console.WriteLine("Calling ExportArmsAsync()");
            var ExportArmsAsyncResult = redcap_api_1_1_0.ExportArmsAsync(_token, Content.Arm, ReturnFormat.json, arms, OnErrorFormat.json).Result;
            Console.WriteLine($"ExportArmsAsyncResult: {JsonConvert.DeserializeObject(ExportArmsAsyncResult)}");
            #endregion ExportArmsAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ImportArmsAsync()
            var ImportArmsAsyncData = CreateArms(count: 3);
            Console.WriteLine("Calling ImportArmsAsync()");
            var ImportArmsAsyncResult = redcap_api_1_1_0.ImportArmsAsync(_token, Content.Arm, Override.False, RedcapAction.Import, ReturnFormat.json, ImportArmsAsyncData, OnErrorFormat.json).Result;
            Console.WriteLine($"ImportArmsAsyncResult: {JsonConvert.DeserializeObject(ImportArmsAsyncResult)}");
            #endregion ImportArmsAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region DeleteArmsAsync()
            var DeleteArmsAsyncData = ImportArmsAsyncData.Select(x => x.ArmNumber).ToArray();
            Console.WriteLine("Calling DeleteArmsAsync()");
            var DeleteArmsAsyncResult = redcap_api_1_1_0.DeleteArmsAsync(_token, Content.Arm, RedcapAction.Delete, DeleteArmsAsyncData).Result;
            Console.WriteLine($"DeleteArmsAsyncResult: {JsonConvert.DeserializeObject(DeleteArmsAsyncResult)}");
            #endregion DeleteArmsAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ExportEventsAsync()
            var ExportEventsAsyncData = new string[] { "1" };
            Console.WriteLine("Calling ExportEventsAsync()");
            var ExportEventsAsyncResult = redcap_api_1_1_0.ExportEventsAsync(_token, Content.Event, ReturnFormat.json, ExportEventsAsyncData, OnErrorFormat.json).Result;
            Console.WriteLine($"ExportEventsAsyncResult: {JsonConvert.DeserializeObject(ExportEventsAsyncResult)}");
            #endregion ExportEventsAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ImportEventsAsync()
            Console.WriteLine("Calling ExportEventsAsync()");
            var eventList = new List <RedcapEvent> {
                new RedcapEvent {
                    EventName        = "baseline",
                    ArmNumber        = "1",
                    DayOffset        = "1",
                    MinimumOffset    = "0",
                    MaximumOffset    = "0",
                    UniqueEventName  = "baseline_arm_1",
                    CustomEventLabel = "hello baseline"
                },
                new RedcapEvent {
                    EventName        = "clinical",
                    ArmNumber        = "1",
                    DayOffset        = "1",
                    MinimumOffset    = "0",
                    MaximumOffset    = "0",
                    UniqueEventName  = "clinical_arm_1",
                    CustomEventLabel = "hello clinical"
                }
            };
            var ImportEventsAsyncResult = redcap_api_1_1_0.ImportEventsAsync(_token, Content.Event, RedcapAction.Import, Override.False, ReturnFormat.json, eventList, OnErrorFormat.json).Result;
            Console.WriteLine($"ImportEventsAsyncResult: {ImportEventsAsyncResult}");
            #endregion ImportEventsAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();


            #region DeleteEventsAsync()
            var DeleteEventsAsyncData = new string[] { "baseline_arm_1" };
            Console.WriteLine("Calling DeleteEventsAsync()");
            var DeleteEventsAsyncResult = redcap_api_1_1_0.DeleteEventsAsync(_token, Content.Event, RedcapAction.Delete, DeleteEventsAsyncData).Result;
            Console.WriteLine($"DeleteEventsAsyncResult: {DeleteEventsAsyncResult}");
            #endregion DeleteEventsAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();


            #region ExportFieldNamesAsync()
            Console.WriteLine("Calling ExportFieldNamesAsync(), first_name");
            var ExportFieldNamesAsyncResult = redcap_api_1_1_0.ExportFieldNamesAsync(_token, Content.ExportFieldNames, ReturnFormat.json, "first_name", OnErrorFormat.json).Result;
            Console.WriteLine($"ExportFieldNamesAsyncResult: {ExportFieldNamesAsyncResult}");
            #endregion ExportFieldNamesAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();


            #region ImportFileAsync()
            var           recordId        = "1";
            var           fileName        = "Demographics_TestProject_DataDictionary.csv";
            DirectoryInfo myDirectory     = new DirectoryInfo(Environment.CurrentDirectory);
            string        parentDirectory = myDirectory.Parent.FullName;
            var           parent          = Directory.GetParent(parentDirectory).FullName;
            var           filePath        = Directory.GetParent(parent).FullName + @"\Docs\";
            Console.WriteLine($"Calling ImportFileAsync(), {fileName}");
            var ImportFileAsyncResult = redcap_api_1_1_0.ImportFileAsync(_token, Content.File, RedcapAction.Import, recordId, fieldName, eventName, null, fileName, filePath, OnErrorFormat.json).Result;
            Console.WriteLine($"ImportFileAsyncResult: {ImportFileAsyncResult}");
            #endregion ImportFileAsync()


            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ExportFileAsync()
            Console.WriteLine($"Calling ExportFileAsync(), {fileName} for field name {fieldName}, not save the file.");
            var ExportFileAsyncResult = redcap_api_1_1_0.ExportFileAsync(_token, Content.File, RedcapAction.Export, recordId, fieldName, eventName, null, OnErrorFormat.json).Result;
            Console.WriteLine($"ExportFileAsyncResult: {ExportFileAsyncResult}");
            #endregion ExportFileAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ExportFileAsync()
            var filedDownloadPath = @"C:\redcap_download_files";
            Console.WriteLine($"Calling ExportFileAsync(), {fileName} for field name {fieldName}, saving the file.");
            var ExportFileAsyncResult2 = redcap_api_1_1_0.ExportFileAsync(_token, Content.File, RedcapAction.Export, recordId, fieldName, eventName, null, OnErrorFormat.json, filedDownloadPath).Result;
            Console.WriteLine($"ExportFileAsyncResult2: {ExportFileAsyncResult2}");
            #endregion ExportFileAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region DeleteFileAsync()
            Console.WriteLine($"Calling DeleteFileAsync(), deleting file: {fileName} for field: {fieldName}");
            var DeleteFileAsyncResult = redcap_api_1_1_0.DeleteFileAsync(_token, Content.File, RedcapAction.Delete, recordId, fieldName, eventName, "1", OnErrorFormat.json).Result;
            Console.WriteLine($"DeleteFileAsyncResult: {DeleteFileAsyncResult}");
            #endregion DeleteFileAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ExportInstrumentsAsync()
            Console.WriteLine($"Calling DeleteFileAsync()");
            var ExportInstrumentsAsyncResult = redcap_api_1_1_0.ExportInstrumentsAsync(_token, Content.Instrument, ReturnFormat.json).Result;
            Console.WriteLine($"ExportInstrumentsAsyncResult: {ExportInstrumentsAsyncResult}");
            #endregion ExportInstrumentsAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ExportPDFInstrumentsAsync()
            Console.WriteLine($"Calling ExportPDFInstrumentsAsync(), returns raw");
            var ExportPDFInstrumentsAsyncResult = redcap_api_1_1_0.ExportPDFInstrumentsAsync(_token, Content.Pdf, recordId, eventName, "demographics", true, OnErrorFormat.json).Result;
            Console.WriteLine($"ExportInstrumentsAsyncResult: {JsonConvert.SerializeObject(ExportPDFInstrumentsAsyncResult)}");
            #endregion ExportPDFInstrumentsAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ExportPDFInstrumentsAsync()
            Console.WriteLine($"Calling ExportPDFInstrumentsAsync(), saving pdf file to {filedDownloadPath}");
            var ExportPDFInstrumentsAsyncResult2 = redcap_api_1_1_0.ExportPDFInstrumentsAsync(_token, recordId, eventName, "demographics", true, filedDownloadPath, OnErrorFormat.json).Result;
            Console.WriteLine($"ExportPDFInstrumentsAsyncResult2: {ExportPDFInstrumentsAsyncResult2}");
            #endregion ExportPDFInstrumentsAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            //#region ExportInstrumentMappingAsync()
            //Console.WriteLine($"Calling ExportInstrumentMappingAsync()");
            //var armsToExportInstrumentMapping = arms;
            //var ExportInstrumentMappingAsyncResult = redcap_api_1_1_0.ExportInstrumentMappingAsync(_token, Content.FormEventMapping, ReturnFormat.json, armsToExportInstrumentMapping, OnErrorFormat.json).Result;
            //Console.WriteLine($"ExportInstrumentMappingAsyncResult: {ExportInstrumentMappingAsyncResult}");
            //#endregion ExportInstrumentMappingAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ImportInstrumentMappingAsync()
            var importInstrumentMappingData = new List <FormEventMapping> {
                new FormEventMapping {
                    arm_num = "1", unique_event_name = "clinical_arm_1", form = "demographics"
                }
            };
            Console.WriteLine($"Calling ImportInstrumentMappingAsync()");
            var ImportInstrumentMappingAsyncResult = redcap_api_1_1_0.ImportInstrumentMappingAsync(_token, Content.FormEventMapping, ReturnFormat.json, importInstrumentMappingData, OnErrorFormat.json).Result;
            Console.WriteLine($"ImportInstrumentMappingAsyncResult: {ImportInstrumentMappingAsyncResult}");
            #endregion ImportInstrumentMappingAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ExportMetaDataAsync()
            Console.WriteLine($"Calling ExportMetaDataAsync()");
            var ExportMetaDataAsyncResult = redcap_api_1_1_0.ExportMetaDataAsync(_token, Content.MetaData, ReturnFormat.json, null, null, OnErrorFormat.json).Result;
            Console.WriteLine($"ExportMetaDataAsyncResult: {ExportMetaDataAsyncResult}");
            #endregion ExportMetaDataAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ImportMetaDataAsync()

            /*
             * This imports 1 field into the data dictionary
             */
            var importMetaData = new List <RedcapMetaData> {
                new RedcapMetaData {
                    field_name = "first_name", form_name = "demographics", field_type = "text", field_label = "First Name"
                }
            };
            Console.WriteLine($"Not calling ImportMetaDataAsync(), still change data dictionary to include 1 field");
            //var ImportMetaDataAsyncResult = redcap_api_1_0_7.ImportMetaDataAsync(_token, "metadata", ReturnFormat.json, importMetaData, OnErrorFormat.json).Result;
            //Console.WriteLine($"ImportMetaDataAsyncResult: {ImportMetaDataAsyncResult}");
            #endregion ImportMetaDataAsync()

            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region CreateProjectAsync()
            var projectData = new List <RedcapProject> {
                new RedcapProject {
                    project_title = "Amazing Project ", purpose = ProjectPurpose.Other, purpose_other = "Test"
                }
            };
            Console.WriteLine($"Calling CreateProjectAsync(), creating a new project with Amazing Project as title, purpose 1 (other) ");
            Console.WriteLine($"-----------------------Notice the use of SUPER TOKEN------------------------");
            var CreateProjectAsyncResult = redcap_api_1_1_0.CreateProjectAsync(_superToken, Content.Project, ReturnFormat.json, projectData, OnErrorFormat.json, null).Result;
            Console.WriteLine($"CreateProjectAsyncResult: {CreateProjectAsyncResult}");
            #endregion CreateProjectAsync()
            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ImportProjectInfoAsync()
            var projectInfo = new RedcapProjectInfo {
                ProjectTitle = "Updated Amazing Project ", Purpose = ProjectPurpose.QualityImprovement, SurveysEnabled = 1
            };
            Console.WriteLine($"Calling ImportProjectInfoAsync()");
            var ImportProjectInfoAsyncResult = redcap_api_1_1_0.ImportProjectInfoAsync(_token, Content.ProjectSettings, ReturnFormat.json, projectInfo).Result;
            Console.WriteLine($"ImportProjectInfoAsyncResult: {ImportProjectInfoAsyncResult}");
            #endregion ImportProjectInfoAsync()
            Console.WriteLine("----------------------------Press Enter to Continue-------------");
            Console.ReadLine();

            #region ExportProjectInfoAsync()
            Console.WriteLine($"Calling ExportProjectInfoAsync()");
            var ExportProjectInfoAsyncResult = redcap_api_1_1_0.ExportProjectInfoAsync(_token, Content.ProjectSettings, ReturnFormat.json).Result;
            Console.WriteLine($"ExportProjectInfoAsyncResult: {ExportProjectInfoAsyncResult}");
            #endregion ExportProjectInfoAsync()

            Console.WriteLine("----------------------------Demo completed! Press Enter to Exit-------------");
            Console.ReadLine();
        }