Wednesday, August 15, 2012

C# CSV Mapping and WebClient Upload

In this tutorial, I'm going to give an example of creating a comma delimited csv formatted string from an object, and an example of uploading that object using WebClient. This is actually a continuation of my first post about replicating a curl request in C# without any extra libraries.

I'm using an object called MyObject.  This is a made up object for the example.  The fields in your classes must match those of the fields in your table in order for this code to work properly.

The line csvData = csvData.Substring(0, csvData.Length - 1); is used to cut off the last comma in each line of the csv output.
   
     public string MapCSVToTable(MyObject obj)

        {

            string csvData = "";


            // Loop through the object field names to use as the CSV header line.  
              //Descriptor allows us to get advanced information about an object such as field names and values.
            foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj.FirstOrDefault()))

            {
                
                csvData += descriptor.Name + ",";

            }

            csvData = csvData.Substring(0, csvData.Length - 1);


            //  Create a new line break.  
            csvData += Environment.NewLine;


             //  Loop through the object and get the values.
            foreach (var a in obj)

            {

                foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(a))

                {

                 

                    if (descriptor.GetValue(a) != null)

                    {

                        csvData += descriptor.GetValue(a) + ",";

                    }

                    else

                    {

                        csvData += ",";

                    }

                }

                csvData = csvData.Substring(0, csvData.Length - 1);
                
                // Create a new line break;
                csvData += Environment.NewLine;

            }

            return csvData;

        }

The UpdateTable function takes 3 parameters. The tableName specifies which table you would to affect, mappedData is the CSV string created in our first function, and httpMethod allows for you to specify "PUT" or "POST". "PUT" will update the record and "POST" will create a new record.
       public void UpdateTable(string tableName, string mappedData, string httpMethod)
        {
            // Create a new WebClient.
            WebClient client = new WebClient();
            // Encode the mapped CSV data into bytes.
            byte[] bytes = Encoding.UTF8.GetBytes(mappedData);
            
            string UserName = "username";
            string Password = "password";

            string authInfo = UserName + ":" + Password;

            client.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));
            // Call UploadDate using your url, table name, method, and bytes created from your mapped data.
            byte[] responseBytes = client.UploadData("https://something.something/function/" + tableName, httpMethod, bytes);

            // The result is for debugging purposes.  It will show detailed error or success messages.
            string result = Encoding.UTF8.GetString(responseBytes);
        }
Usage example:


MyObject obj = new My Object();
obj.name = "Bruce Wayne";
obj.occupation = "Philanthropist Billionaire";
obj.emergencyContact = "Alfred Pennyworth";
obj.phone = "bat symbol";
obj.status = "MIA";

string mappedData = MapCSVToTable(obj);

UpdateTable("people", mappedData, "PUT");

CSV Example Output:


name, occupation, emergencyContact, phone, status
"Bruce Wayne", "Philanthropist Billionaire", "Alfred Pennyworth", "bat symbol", "MIA"