cancel
Showing results for 
Search instead for 
Did you mean: 
Due to an issue with YouTube, inserting videos in your emails is showing an error. Until they are able to resolve this issue, we recommend using a different video hosting service. We will continue to monitor this outage and update you as we have more information.

Bulk Activities - Add contacts - Need Help

SOLVED
Moderator

Re: Bulk Activities - Add contacts - Need Help

We don't currently have any examples of doing a file import with C# currently, we are in the process of adding this to our wrapper library and will hopefully have this in the next few weeks.  Follow our Github repo and you'll see when this is added: https://github.com/constantcontact/.net-sdk

Dave Berard
Senior Product Manager, Constant Contact
Occasional Contributor

Re: Bulk Activities - Add contacts - Need Help

It's nice that you guys will be adding it to the Github repository but I was wondering if you could look at my code and see what I'm doing wrong. It's VB.net. I think it's the whole Oauth with passing in the http headers thats the problem. Thanks a head of time.

 

Imports System.IO
Imports System.Text
Imports System.Collections.Specialized

 

Private Sub tyrout()

        Dim filename As String = ""

        Dim boundary As String = Guid.NewGuid().ToString()

        Dim request As HttpWebRequest = TryCast(HttpWebRequest.Create("https://api.constantcontact.com/v2/activities/addcontacts"), HttpWebRequest)

        request.Method = "POST"  

       request.ContentType = String.Format("multipart/form-data")

        request.Accept = "application/json"

        'request.PreAuthenticate = True

        Dim sb As New StringBuilder()

        sb.AppendFormat("--{0}", boundary)

        sb.AppendFormat(vbCr & vbLf)

        filename = "C:\Development\constantcontact\emailkust.csv"

        sb.AppendFormat("Content-Disposition: form-data; name=""media""; filename=""" & filename & """")

        sb.AppendFormat(vbCr & vbLf)

        sb.AppendFormat("Authorization:  Bearer ") 'place the key from oauth here is my guess

        sb.AppendFormat(vbCr & vbLf)    

        sb.AppendFormat("content-Type:  multipart/form-data")

        sb.AppendFormat(vbCr & vbLf)

        sb.AppendFormat("lists:  75") 'list number I guess is where it should go

        sb.AppendFormat(vbCr & vbLf)

        sb.AppendFormat("api_key: ") 'place the api key here I think or should it go on the http path?

        sb.AppendFormat(vbCr & vbLf)

        Using fs As New FileStream(filename, FileMode.Open, FileAccess.Read)  

           Dim contents As Byte() = New Byte(fs.Length - 1) {}

            fs.Read(contents, 0, contents.Length)

            sb.Append(Encoding.[Default].GetString(contents))

        End Using

        sb.AppendFormat(vbCr & vbLf)

        sb.AppendFormat("--{0}--", boundary)

        Dim fulldata As Byte() = Encoding.[Default].GetBytes(sb.ToString())

        request.ContentLength = fulldata.Length

        Using sw As Stream = request.GetRequestStream()

            sw.Write(fulldata, 0, fulldata.Length)

        End Using       

  Dim response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)        

Using sr As New StreamReader(response.GetResponseStream())

            MessageBox.Show(sr.ReadToEnd())       

  End Using    

End Sub

 

The csv file looks like this

"EMAIL","LAST NAME","FIRST NAME"
"1@one.org","1","1"
"2@two.org","2","2"
"3@three.org","3","3"
"4@four.org","4","4"

Moderator

Re: Bulk Activities - Add contacts - Need Help

The one thing I see immediately is that api_key is a query parameter for the URL, not a header parameter.  Our support team will check out the code though as well to see if we can get you up and running.

Dave Berard
Senior Product Manager, Constant Contact
Occasional Contributor

Re: Bulk Activities - Add contacts - Need Help

Thank you guys for the help. I've included the code that you guys have helped me with so it can be of help for those in the future.

 

Note about the api_key. Looking at the java sample that is posted to follow I see/saw no mention of even needing/using the api-key. I was just throwing everything I could think of at this and figured since the Bearer code went in the http header that maybe the api_key should also since it didn't appear to be needed. Although I do have to say I may have had it in the right place but had something else wrong at one point in all the tries I went thru before asking for help.  

 

Either way I would like to thank you for the support.  

 

VB.net VS 2010, framework 3.5

 

Imports System.IO
Imports System.Text
Imports System.Collections.Specialized
Private Sub FileUpload()
        Dim filename As String = ""
        ' Added -- to boundary for simplicity
        Dim boundary As String = "--" & Guid.NewGuid().ToString()
 
        ' The API key needs to be appended to the request URI
        Dim request As HttpWebRequest = TryCast(HttpWebRequest.Create("https://api.constantcontact.com/v2/activities/addcontacts?api_key=APIKEYHERE"), HttpWebRequest)
        request.Method = "POST"
        request.ContentType = String.Format("multipart/form-data")
        request.Accept = "application/json"
        'request.PreAuthenticate = True
        request.Headers.Add("Authorization:  Bearer BEARERTOKEN"' Add your Access Token here
        ' I Also changed from AppendFormat for all lines to simply using AppendLine to shorten the content. 
        ' Feel free to change it back where you want to merge variables.
 
        filename = "C:\Development\constantcontact\emailkust.csv"
 
        ' In order to get the request right, there are three request parts to add:
        ' file_name - The filename
        ' lists - comma separated list of list IDs
        ' data - The actual file data
 
        Dim sb As New StringBuilder()
        sb.AppendLine(boundary)
        sb.AppendLine("content-disposition: form-data; name=""file_name""")
        sb.AppendLine()
        sb.AppendLine("emailkust.csv"'filename
        sb.AppendLine(boundary)
        sb.AppendLine("content-disposition: form-data; name=""lists""")
        sb.AppendLine()
        sb.AppendLine("1"' List Number
        sb.AppendLine(boundary)
 
        sb.AppendLine("content-disposition: file; name=""data"" filename=""emailkust.csv""")
        sb.AppendLine("Content-Type: text/csv")
        sb.AppendLine()
        Using fs As New FileStream(filename, FileMode.Open, FileAccess.Read)
            Dim contents As Byte() = New Byte(fs.Length - 1) {}
            fs.Read(contents, 0, contents.Length)
            sb.Append(Encoding.[Default].GetString(contents))
        End Using
 
        sb.AppendLine(boundary & "--")
        Dim fulldata As Byte() = Encoding.[Default].GetBytes(sb.ToString())
        ' Uncomment the next line to dump the multipart request contents to a file for debugging.
        ' My.Computer.FileSystem.WriteAllText("C:\constantcontact\test.txt", sb.ToString(), True)
        request.ContentLength = fulldata.Length
        Using sw As Stream = request.GetRequestStream()
            sw.Write(fulldata, 0, fulldata.Length)
        End Using
        ' Exception Handling was added so that I could display the error 
        Try
            Dim response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
            Using sr As New StreamReader(response.GetResponseStream())
                MessageBox.Show(sr.ReadToEnd())
            End Using
        Catch e As WebException
            Using sr As New StreamReader(e.Response.GetResponseStream())
                MessageBox.Show("Error Message:" & e.Message & vbCr & vbLf & "Error Body: " & sr.ReadToEnd(), "Web Error"MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Using
        End Try
 
    End Sub

 

Honored Contributor

Re: Bulk Activities - Add contacts - Need Help

Thanks so much for posting this, I'm sure it will be useful for others as well!

 

Sincerely,

Elijah G.

API Support Specialist

Elijah G.
API Support Engineer
Occasional Contributor

Re: Bulk Activities - Add contacts - Need Help

Hi Dave,

 

I am having problem with the custom fields again.  In reference to the Java code that I have posted in the very beginning of this thread when I make the following changes (as you had suggested earlier) the code works fine:

 

// Set Member Id
CustomField objCustomField = new CustomField();
List<CustomField> lsCustomField = new ArrayList<CustomField>();
objCustomField.setName("CUSTOM FIELD 1");
objCustomField.setValue(alMemberId.get(i).toString());
lsCustomField.add(objCustomField);
objContactData.setCustomFields(lsCustomField);

 

However the following does not work:

 

// Set Member Id
CustomField objCustomField = new CustomField();
List<CustomField> lsCustomField = new ArrayList<CustomField>();
objCustomField.setName("CUSTOM FIELD 2");
objCustomField.setValue(alMemberId.get(i).toString());
lsCustomField.add(objCustomField);
objContactData.setCustomFields(lsCustomField);

 

It is also true that other than "CUSTOM FIELD 1" the code is not working for the other fields.  In other words apart from the first custom field I am unable to set data for rest of the custom fields.  Can you please look into this problem and have it solved at your earliest?

 

Thanks & Regards,

Srinivas

Regular Advisor

Re: Bulk Activities - Add contacts - Need Help

Hi there,

 

If you're looking to use multiple custom fields,  they both need to be added to the list before being set in the ContactData object.  This should do the trick:

 

// Set Member Id
            CustomField objCustomField = new CustomField();
            List<CustomField> lsCustomField = new ArrayList<CustomField>();
            objCustomField.setName("CUSTOM FIELD 1");
            objCustomField.setValue(alMemberId.get(i).toString());
            lsCustomField.add(objCustomField);
            //objContactData.setCustomFields(lsCustomField);

            CustomField objCustomField2 = new CustomField();
            //List<CustomField> lsCustomField = new ArrayList<CustomField>();
            objCustomField2.setName("CUSTOM FIELD 2");
            objCustomField2.setValue(alMemberId.get(i).toString());
            lsCustomField.add(objCustomField2);
            objContactData.setCustomFields(lsCustomField);

// Add contact to contact list
            lsContactData.add(objContactData);

 

Highlighted
Occasional Contributor

Re: Bulk Activities - Add contacts - Need Help

Hi AndrewB776,

 

Thanks a ton for the solution.  Yes, after making the changes in my code as you had suggested I am able to load data into multiple custom fields correctly.

 

Thanks & Regards,

Srinivas