cancel
Showing results for 
Search instead for 
Did you mean: 

Create Contact - The remote server returned an error: (500) Internal Server Error.

Occasional Contributor

Create Contact - The remote server returned an error: (500) Internal Server Error.

Hi,

 

I am getting a lis of contacts from my database using a stored procedure, afterwhich I either create or update these contacts. However, I am having a strange  problem. For example, I have 5 contacts I need to create and when I run my program the first contact gets created and throws error 500 on Utility.CreateNewContact() for contact 2. I exit out and re-run my program, it updates contact 2 and throws an error on contact3 and so on.

 

I do not know what I am doing wrong. Is it because I am updating the contact to 2 different lists? Please help!

 

I have noticed that it throws that error on only some Contacts. I have used trim wherever applicable.

I also see that in the Utility.cs file, it throws a ConstantException(e.Message, e);

 

 

public void CreateContact(Contact contact, string mode, string client_id)
{
int client_id1 = Convert.ToInt32(client_id);

if (mode == "newClient")
{
//Create a new contact
ContactOptInList newList1 = new ContactOptInList();
contact.OptInSource = ContactOptSource.ActionByContact;
newList1.ContactList = new ContactList("39");
contact.ContactLists.Add(newList1);//check the contact here
ContactOptInList newList2 = new ContactOptInList();
contact.OptInSource = ContactOptSource.ActionByContact;
newList2.ContactList = new ContactList("10");
contact.ContactLists.Add(newList2);//check the contact here
contact.Status = ContactStatus.Active;
Utility.CreateNewContact(authdata, contact);
//Updates the client information field Constant_Contact to ‘Y’ to show that the client record has been uploaded to Constant Contact
DataTable dtUpdateCustomers = new DataTable();
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@ClientId", client_id1);
dtUpdateCustomers = dbConn.ExecuteDataTable("sp_SetConstantContactUpdate", param);

 

6 REPLIES 6
CTCT Employee

Re: Create Contact - The remote server returned an error: (500) Internal Server Error.

Hi,

 

I got this code to work on my end--of course I am running the program each time I want to add a new contact, not adding multiple email addresses at a time.  If you want to only run the program/script one time and have it add multiple email addresses,  you would need to create an array to store the email addresses you wish to add, then do a foreach loop to add each of them in turn.  I wouldn't do this for a very large number of contacts though (that would be better handled by a bulk import activity).  This is the code that works for me (same as yours, I just instantiated the contact, which you had probably done previously).  The list handling is correct--the new contact was created and belongs to 2 lists in my account.  

 

Contact contact = new Contact();
contact.EmailAddress = "testemail11202012@test.com";

ContactOptInList newList1 = new ContactOptInList();
contact.OptInSource = ContactOptSource.ActionByContact;
newList1.ContactList = new ContactList("1");
contact.ContactLists.Add(newList1);//check the contact here

ContactOptInList newList2 = new ContactOptInList();
contact.OptInSource = ContactOptSource.ActionByContact;
newList2.ContactList = new ContactList("18");
contact.ContactLists.Add(newList2);//check the contact here

contact.Status = ContactStatus.Active;
Utility.CreateNewContact(authdata, contact);

 

 

Perhaps it's an issue with the database handling of contacts.  Also, are you checking to see if the contact's email address exists in the database prior to adding it?  Trying to add an email that already exists would result in an error.

 

Best Regards,

Shannon W.

API Support Specialist

Occasional Contributor

Re: Create Contact - The remote server returned an error: (500) Internal Server Error.

Thanks for your reply, maybe this code will help understand how I am adding the contacts.

 

 DataTable dtCustomersNewClient = new DataTable();
        dtCustomersNewClient = dbConn.ExecuteDataTable("sp_GetFirstVisitClientsEmail", null);
        foreach (DataRow row1 in dtCustomersNewClient.Rows)
        {
 string client_id = row1["ClientId"].ToString();
  SearchContactByEmail(customer_email, contact, mode, client_id);
//I perform the above function only after email is valid
}

    public void SearchContactByEmail(string customer_email, Contact contact, string mode, string client_id)
    {
        string status = null;

        //Search Contact by Email
        List<string> email = new List<string>();
        email.Add(customer_email);
        IList<Contact> myContact = Utility.SearchContactByEmail(authdata, email, out nextChunkId);
      
        if (myContact.Count == 0)//Contact Does not exist
        {
                //Create a new Contact
                CreateContact(contact, mode, client_id);
        }

        else
        {
                //Update Contact if contact already exists
                UpdateContact(myContact, mode, client_id);
        }
    }

createcontact();
updatecontact();

 I understand this code works only sometimes, but what I do not understand is why it fails on certain contacts(Internal 500 server error) but when I rerun the program that contact gets added. I am getting a list of contacts from the stored procedure and am then using a foreach for each contact to either add or update.

 

The idea is that this progam automatically runs every 15 minutes and fetches new contacts which is then added or updated to constant contact.

 

Could you also point out to the latest dll's for Constant Contact. Thanks a lot for your help.

 

CTCT Employee

Re: Create Contact - The remote server returned an error: (500) Internal Server Error.

Hi,

 

Your logic looks good to me.  I can think of 2 possible causes.  Are you calling the updatecontact() and createcontact() functions at the bottom regardless of whether the contact is new or existing?  Calling a function that doesn't have all of the contact object information it needs could be resulting in the error.

 

Otherwise, I have reason to be concerned about our special character handling (encoding) in the .NET wrapper for usernames that contain spacial characters.  Does your username contain anything other than numbers and letters?  

 

Best Regards,

Shannon W.

API Support Specialist

Occasional Contributor

Re: Create Contact - The remote server returned an error: (500) Internal Server Error.

Thanks a lot for your quick response.

Well, I really don't know what might be causing the problem. Our username has only letters in it. (Is that the one we use in the authentication?) and I tried moving the functions Create and Update above, no change. It adds a few contacts and throws an error on Utility.Create. What do you think I could do to make this work? Or what am I doing wrong? I am running out of time! Phew!

 

I am  posting my complete code here just incase it helps you.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ConstantContactBO;
using ConstantContactUtility;
using UploadContactForm.App_Code;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;


public partial class WebForm1 : System.Web.UI.Page
{
    AuthenticationData authdata = new AuthenticationData();

    string nextChunkId;
    private dbConnection dbConn = new dbConnection();


    protected void Page_Load(object sender, EventArgs e)
    {
        //Authentication Details
        authdata.Username = "*";
        authdata.Password = "*";
        authdata.ApiKey = "*";

        if (!Page.IsPostBack)
        {
            //Get user Contact List collection
            IList<ContactList> lists = Utility.GetUserContactListCollection(authdata, out nextChunkId);
            GetNewClientInformation();
        }
    }

    public void GetNewClientInformation()
    {
        ConstantContactBO.Contact contact = new ConstantContactBO.Contact();
        string salon_visited = null;
        string mode = "newClient";

        string hair_cutter_fn = null;
        string hair_cutter_ln = null;
        string hair_cutter_service = null;

        string chemical_specialist_fn = null;
        string chemical_specialist_ln = null;
        string chemical_service = null;

        string keratin_specialist_fn = null;
        string keratin_specialist_ln = null;
        string keratin_service = null;

        string extensions_specialist_fn = null;
        string extensions_specialist_ln = null;
        string extensions_service = null;

        DataTable dtCustomersNewClient = new DataTable();
        dtCustomersNewClient = dbConn.ExecuteDataTable("sp_GetFirstVisitClientsEmail", null);
        foreach (DataRow row1 in dtCustomersNewClient.Rows)
        {
            string client_id = row1["ClientId"].ToString();

            if (row1["ServiceCategory"].ToString() == "Hair Cutting")
            {
                if (!String.IsNullOrEmpty(row1["EmployeeFirstName"].ToString()))
                {
                    hair_cutter_fn = row1["EmployeeFirstName"].ToString().Trim();
                }
                if (!String.IsNullOrEmpty(row1["EmployeeLastName"].ToString()))
                {
                    hair_cutter_ln = row1["EmployeeLastName"].ToString().Trim();
                }
                if (!String.IsNullOrEmpty(row1["ServiceDone"].ToString()))
                {
                    hair_cutter_service = row1["ServiceDone"].ToString().Trim();
                }
            }

            if ((row1["ServiceCategory"].ToString() == "Hair Coloring") || (row1["ServiceCategory"].ToString() == "Permanent Waving"))
            {
                if (!String.IsNullOrEmpty(row1["EmployeeFirstName"].ToString()))
                {
                    chemical_specialist_fn = row1["EmployeeFirstName"].ToString().Trim();
                }
                if (!String.IsNullOrEmpty(row1["EmployeeLastName"].ToString()))
                {
                    chemical_specialist_ln = row1["EmployeeLastName"].ToString().Trim();
                }
                if (!String.IsNullOrEmpty(row1["ServiceDone"].ToString()))
                {
                    chemical_service = row1["ServiceDone"].ToString().Trim();
                }
            }

            if (row1["ServiceCategory"].ToString() == "Hair Extensions")
            {
                if (!String.IsNullOrEmpty(row1["EmployeeFirstName"].ToString()))
                {
                    extensions_specialist_fn = row1["EmployeeFirstName"].ToString().Trim();
                }
                if (!String.IsNullOrEmpty(row1["EmployeeLastName"].ToString()))
                {
                    extensions_specialist_ln = row1["EmployeeLastName"].ToString().Trim();
                }
                if (!String.IsNullOrEmpty(row1["ServiceDone"].ToString()))
                {
                    extensions_service = row1["ServiceDone"].ToString().Trim();
                }
            }

            if (row1["ServiceCategory"].ToString() == "Keratin")
            {
                if (!String.IsNullOrEmpty(row1["EmployeeFirstName"].ToString()))
                {
                    keratin_specialist_fn = row1["EmployeeFirstName"].ToString().Trim();
                }
                if (!String.IsNullOrEmpty(row1["EmployeeLastName"].ToString()))
                {
                    keratin_specialist_ln = row1["EmployeeLastName"].ToString().Trim();
                }
                if (!String.IsNullOrEmpty(row1["ServiceDone"].ToString()))
                {
                    keratin_service = row1["ServiceDone"].ToString().Trim();
                }
            }

            //Get Customer Information
            if (!String.IsNullOrEmpty(Convert.ToString(row1["ClientFirstName"])))
            {
                contact.FirstName = Convert.ToString(row1["ClientFirstName"]).Trim();
            }
            if (!String.IsNullOrEmpty(Convert.ToString(row1["ClientLastName"])))
            {
                contact.LastName = Convert.ToString(row1["ClientLastName"]).Trim(); ;
            }
            if (!String.IsNullOrEmpty(Convert.ToString(row1["ClientEmail"])))
            {
                contact.EmailAddress = Convert.ToString(row1["ClientEmail"]).Trim();
            }
            if (!String.IsNullOrEmpty(row1["Store"].ToString()))
            {
                salon_visited = row1["Store"].ToString().Trim();
            }
            if (!String.IsNullOrEmpty(Convert.ToString(row1["ClientId"])))
            {
                contact.CustomField2 = Convert.ToString(row1["ClientId"]).Trim();
            }
            if (!String.IsNullOrEmpty(hair_cutter_fn))
            {
                contact.CustomField4 = hair_cutter_fn.Trim();
            }
            if (!String.IsNullOrEmpty(hair_cutter_ln))
            {
                contact.CustomField3 = salon_visited.Trim();
            }
            if (!String.IsNullOrEmpty(hair_cutter_service))
            {
                contact.CustomField6 = hair_cutter_service.Trim();
            }
            if (!String.IsNullOrEmpty(chemical_specialist_fn))
            {
                contact.CustomField7 = chemical_specialist_fn.Trim();
            }
            if (!String.IsNullOrEmpty(chemical_specialist_ln))
            {
                contact.CustomField8 = chemical_specialist_ln.Trim();
            }
            if (!String.IsNullOrEmpty(chemical_service))
            {
                contact.CustomField9 = chemical_service.Trim();
            }
            if (!String.IsNullOrEmpty(extensions_specialist_fn))
            {
                contact.CustomField10 = extensions_specialist_fn.Trim();
            }
            if(!String.IsNullOrEmpty(extensions_specialist_ln))
            {
                contact.CustomField11 = extensions_specialist_ln.Trim();
            }
            if(!String.IsNullOrEmpty(extensions_service))
            {
                contact.CustomField12 = extensions_service.Trim();
            }
            if (!String.IsNullOrEmpty(keratin_specialist_fn))
            {
                contact.CustomField13 = keratin_specialist_fn.Trim();
            }
            if (!String.IsNullOrEmpty(keratin_specialist_ln))
            {
                contact.CustomField14 = keratin_specialist_ln.Trim();
            }
            if (!String.IsNullOrEmpty(keratin_service))
            {
                contact.CustomField15 = keratin_service.Trim();
            }

            string customer_email=null;
            if (!String.IsNullOrEmpty(Convert.ToString(row1["ClientEmail"])))
            {
                customer_email = Convert.ToString(row1["ClientEmail"]).Trim();
            }
            string mail_status = ValidateEmail(customer_email);
            if (mail_status == "true")
            {
                SearchContactByEmail(customer_email, contact, mode, client_id);
            }
        }
    }
        public void CreateContact(Contact contact, string mode, string client_id)
    {
        int client_id1 = Convert.ToInt32(client_id);
        string x = contact.FirstName;
        string y = contact.LastName;
        string z = contact.EmailAddress;
       
        if (mode == "newClient")
        {
            ContactOptInList newList1 = new ContactOptInList();
            contact.OptInSource = ContactOptSource.ActionByContact;
            newList1.ContactList = new ContactList("40");
            contact.ContactLists.Add(newList1);//check the contact here

            ContactOptInList newList2 = new ContactOptInList();
            contact.OptInSource = ContactOptSource.ActionByContact;
            newList2.ContactList = new ContactList("41");
            contact.ContactLists.Add(newList2);//check the contact here

            contact.Status = ContactStatus.Active;
            Utility.CreateNewContact(authdata, contact);
            //Updates the client information field Constant_Contact to ‘Y’ to show that the client record has been uploaded to Constant Contact
            DataTable dtUpdateCustomers = new DataTable();
            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@ClientId", client_id1);
            dtUpdateCustomers = dbConn.ExecuteDataTable("sp_SetConstantContactUpdate", param);
        }

        else if (mode == "vcNewsLetter")
        {
            ContactOptInList newList2 = new ContactOptInList();
            contact.OptInSource = ContactOptSource.ActionByContact;
            newList2.ContactList = new ContactList("40");
            contact.ContactLists.Add(newList2);//check the contact here
            contact.Status = ContactStatus.Active;
            Utility.CreateNewContact(authdata,contact);

            //Updates the client information field Constant_Contact to ‘Y’ to show that the client record has been uploaded to Constant Contact
            DataTable dtUpdateCustomers = new DataTable();
            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@ClientId", client_id1);
            dtUpdateCustomers = dbConn.ExecuteDataTable("sp_SetConstantContactUpdate", param);
        }
    }

    public void UpdateContact(IList<Contact> myContact, string mode, string client_id)
    {
        int client_id1 = Convert.ToInt32(client_id);
        string status = null;
        string myContactId = myContact[0].Id;
        //Get Contact by ID
        Contact thisContact = Utility.GetContactDetailsById(authdata, myContactId);

        if (!String.IsNullOrEmpty(myContact[0].Status.ToString()))
        {
            status = myContact[0].Status.ToString();
        }
        
        //Get Contact by ID
        if (status != "DoNotMail")
        {
            if (mode == "newClient")
            {
                //Update To List // MAY NOT BE REQUIRED FOR AN UPDATE CHECK
                ContactOptInList newList1 = new ContactOptInList();
                thisContact.OptInSource = ContactOptSource.ActionByContact;
                newList1.ContactList = new ContactList("40");
                thisContact.ContactLists.Add(newList1);//check the contact here

                ContactOptInList newList2 = new ContactOptInList();
                thisContact.OptInSource = ContactOptSource.ActionByContact;
                newList2.ContactList = new ContactList("41");
                thisContact.ContactLists.Add(newList2);//check the contact here

                thisContact.Status = ContactStatus.Active;
                Utility.UpdateContactFullForm(authdata, thisContact);

                //Updates the client information field Constant_Contact to ‘Y’ to show that the client record has been uploaded to Constant Contact
                DataTable dtUpdateCustomers = new DataTable();
                SqlParameter[] param = new SqlParameter[1];
                param[0] = new SqlParameter("@ClientId", client_id1);
                dtUpdateCustomers = dbConn.ExecuteDataTable("sp_SetConstantContactUpdate", param);
            }

            else if (mode == "vcNewsLetter")
            {
                ContactOptInList newList2 = new ContactOptInList();
                thisContact.OptInSource = ContactOptSource.ActionByContact;
                newList2.ContactList = new ContactList("41");
                thisContact.ContactLists.Add(newList2);//check the contact here

                thisContact.Status = ContactStatus.Active;
                Utility.UpdateContactFullForm(authdata, thisContact);

                //Updates the client information field Constant_Contact to ‘Y’ to show that the client record has been uploaded to Constant Contact
                DataTable dtUpdateCustomers = new DataTable();
                SqlParameter[] param = new SqlParameter[1];
                param[0] = new SqlParameter("@ClientId", client_id1);
                dtUpdateCustomers = dbConn.ExecuteDataTable("sp_SetConstantContactUpdate", param);
            }
        }
    }

    public void SearchContactByEmail(string customer_email, Contact contact, string mode, string client_id)
    {
        string status = null;

        //Search Contact by Email
        List<string> email = new List<string>();
        email.Add(customer_email);
        IList<Contact> myContact = Utility.SearchContactByEmail(authdata, email, out nextChunkId);
      
        if (myContact.Count == 0)//Contact Does not exist
        {
                //Create a new Contact
                CreateContact(contact, mode, client_id);
        }

        else
        {
                //Update Contact
                UpdateContact(myContact, mode, client_id);
        }
    }

    public string ValidateEmail(string customer_email)
    {
        string mail_status = null;
        string expression = @"^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|" + @"0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\.([a-z]" + @"[a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$";

        Match match = Regex.Match(customer_email, expression, RegexOptions.IgnoreCase);
        if (match.Success)
        {
            mail_status = "true";//Valid Email
        }
        else
        {
            mail_status = "false";//Invalid Email
        }
        return mail_status;
    }

    }

 STACK TRACE

[WebException: The remote server returned an error: (500) Internal Server Error.]
   System.Net.HttpWebRequest.GetResponse() +6440920
   ConstantContactUtility.Utility.GetResponseStream(AuthenticationData authenticationData, Uri address, String requestMethod, String contentType, Byte[] data) in C:\Users\dberard\Desktop\Wrapper\Development\ConstantContactUtility\Utility.cs:1815
   ConstantContactUtility.Utility.GetResponseStream(AuthenticationData authenticationData, Uri address, String requestMethod, String contentType, String data) in C:\Users\dberard\Desktop\Wrapper\Development\ConstantContactUtility\Utility.cs:1780
   ConstantContactUtility.Utility.PostInformation(AuthenticationData authenticationData, Uri address, String data) in C:\Users\dberard\Desktop\Wrapper\Development\ConstantContactUtility\Utility.cs:322
   ConstantContactUtility.Utility.CreateNewContact(AuthenticationData authenticationData, Contact contact) in C:\Users\dberard\Desktop\Wrapper\Development\ConstantContactUtility\Utility.cs:292

[ConstantException: The remote server returned an error: (500) Internal Server Error.]
   ConstantContactUtility.Utility.CreateNewContact(AuthenticationData authenticationData, Contact contact) in C:\Users\dberard\Desktop\Wrapper\Development\ConstantContactUtility\Utility.cs:300
   WebForm1.CreateContact(Contact contact, String mode, String client_id) +268
   WebForm1.SearchContactByEmail(String customer_email, Contact contact, String mode, String client_id) +203
   WebForm1.GetNewClientInformation() +4906
   WebForm1.Page_Load(Object sender, EventArgs e) +159
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
   System.Web.UI.Control.OnLoad(EventArgs e) +92
   System.Web.UI.Control.LoadRecursive() +54
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772

 

Occasional Contributor

Re: Create Contact - The remote server returned an error: (500) Internal Server Error.

Anything?

CTCT Employee

Re: Create Contact - The remote server returned an error: (500) Internal Server Error.

Hi,

 

I apologize that I don't have the time to fully troubleshoot this, but if the error points to credentials, you could try storing your credentials differently--maybe make them public or not in a function at all to see if that helps.  I'm wondering if the call to retrieve the credentials for anything requiring authentication is failing sometimes, or the username isn't available at times that it needs to be accessed -- like when our wrapper constructs the url's for lists, which include your username as below.

 

You could also check your server logs to see the payload and the URL that you're sending to, and that could help determine the issue.  I can recommend fiddler if you don't have access to your server logs.  Our documentation includes XML samples for the payloads that should be sent over.

 

Best Regards,

Shannon W.

API Support Specialist