Wednesday, July 7, 2010

ConstantContact API webservice Sample

ConstantContact API webservice - add your email list directly to ConstantContact email list.
Technology used: C# , asp.net 2.0
In this sample I am uploading first name, last name and email address to constant contact all mailing list.

1. From http://developer.constantcontact.com/license/login you can get api keys.



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
     <div style="margin-left: 30px; margin-top: 10px">
    </div>
    <table style="margin-top: 10px; vertical-align: top">
        <tr>
            <td style="padding-left: 25px; width: 480px; height: 457px;">
                <table style="border-right: green thin solid; border-top: green thin solid; border-left: green thin solid;
                    border-bottom: green thin solid;">
                    <tr>
                        <td style="width: 200px">
                            <asp:Label ID="lblEmail" runat="server" Font-Bold="True" Font-Italic="False" Font-Names="Calibri"
                                Font-Overline="False" Font-Size="11pt" Font-Strikeout="False" Font-Underline="False"
                                Text="Email Address:"></asp:Label>
                        </td>
                        <td align="right">
                            <asp:TextBox ID="txtEmail" runat="server" Font-Names="Calibri" Font-Size="11pt" Width="254px"
                                MaxLength="50" TabIndex="1"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Label ID="lblFirst" runat="server" Font-Bold="True" Font-Italic="False" Font-Names="Calibri"
                                Font-Overline="False" Font-Size="11pt" Font-Strikeout="False" Font-Underline="False"
                                Text="First Name:"></asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="txtFirst" runat="server" Font-Names="Calibri" Font-Size="11pt" Width="254px"
                                MaxLength="50" TabIndex="2"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Label ID="lblLast" runat="server" Font-Bold="True" Font-Italic="False" Font-Names="Calibri"
                                Font-Overline="False" Font-Strikeout="False" Font-Underline="False" Text="Last Name:"
                                Font-Size="11pt"></asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="txtLast" runat="server" Font-Names="Calibri" Font-Size="11pt" Width="254px"
                                MaxLength="50" TabIndex="3"></asp:TextBox>
                        </td>
                    </tr>
                    </table>
            </td>
            <td style="height: 457px">
                <div>
                    <div style="text-align: center">
                        <table>
                            <tr>
                                <td align="center">
                                    <asp:Label ID="lblContactList" runat="server" Font-Bold="True" Font-Names="Calibri"
                                        Font-Size="11pt" Width="416px" Text="Please select the areas of interest for which you would like to receive occasional email from us."></asp:Label>
                                </td>
                            </tr>
                        </table>
                    </div>
                    <asp:Panel ID="contactListsPanel" runat="server" BackColor="White" BorderColor="Green"
                        BorderWidth="1px" Height="39px" Width="117px" ScrollBars="Both">
                        <asp:CheckBoxList ID="chkListContactLists" runat="server" Width="300px" DataTextField="Name"
                            DataValueField="Id" CellSpacing="5" Font-Names="Calibri" Font-Size="11pt">
                        </asp:CheckBoxList>
                    </asp:Panel>
                </div>
            </td>
        </tr>
        <tr>
            <td style="padding-left: 25px; width: 480px; height: 53px;">
                <table>
                    <tr>
                        <td>
                            <asp:Button ID="btnAdd" runat="server" Text="Add Contact" OnClick="btnAdd_Click"
                                Font-Names="Calibri" Font-Size="11pt" />
                            <asp:CustomValidator ID="customValidator" runat="server" Display="None" OnServerValidate="customValidator_ServerValidate">
                            </asp:CustomValidator>
                        </td>
                    </tr>
                </table>
            </td>
            <td style="height: 53px">
                &nbsp;
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
            </td>
        </tr>
    </table>

    </form>
</body>
</html>

code behind

using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using ConstantContactBO;
using ConstantContactUtility;
using UploadContactForm.App_Code;

public partial class Default3 : System.Web.UI.Page
{
    private AuthenticationData AuthenticationData
    {
        get
        {
            if (Session["AuthenticationData"] == null)
            {
                Session.Add("AuthenticationData", ConstantContact.AuthenticationData);
            }
            return (AuthenticationData)Session["AuthenticationData"];
        }
    }
    private List<ContactList> List
    {
        get { return (List<ContactList>)ViewState["contactList"]; }
        set { ViewState["contactList"] = value; }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack) return;

        if (Session["NewContactEmailAddress"] != null)
        {
            // initialize the E-mail Address text box
            txtEmail.Text = (string)Session["NewContactEmailAddress"];
            Session.Remove("NewContactEmailAddress");
        }

        // get user Contact List collection
        List = ConstantContact.GetUserContactListCollection(ClientScript);

        chkListContactLists.DataSource = List;
        chkListContactLists.DataBind();

        for (int i = 0; i < chkListContactLists.Items.Count; i++)
        {
            chkListContactLists.Items[i].Selected = true;
        }
    }


   protected void btnAdd_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
{
return;
}

string[] emailAddress = new string[] { txtEmail.Text.Trim() };
try
{
string nextChunkId;

IList list = Utility.SearchContactByEmail(AuthenticationData, emailAddress, out nextChunkId);
if (list.Count == 0)
{
// create new Contact
Contact contact = GetContactInformation();

Utility.CreateNewContact(AuthenticationData, contact);
// Response.Redirect("~/AddContactConfirmation.aspx");
Label1.Text = "Added";
}
else
{
throw new ConstantException(String.Format(CultureInfo.CurrentCulture,
"Email address \"{0}\" is already a contact", txtEmail.Text.Trim()));
}
}
catch (ConstantException ce)
{
#region display alert message
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(@"");
ClientScript.RegisterStartupScript(typeof(Page), "AlertMessage", stringBuilder.ToString());
#endregion
}
}
protected void customValidator_ServerValidate(object source, ServerValidateEventArgs args)
{

string errorMessage = string.Empty;

if (string.IsNullOrEmpty(txtEmail.Text.Trim()))
{
errorMessage = "Please enter the contact email address.";
args.IsValid = false;
}

if (args.IsValid && !Utility.IsEmail(txtEmail.Text.Trim()))
{
errorMessage = "Please enter a valid contact email address.";
args.IsValid = false;
}

if (args.IsValid)
{
bool selected = true;

foreach (ListItem item in chkListContactLists.Items)
{

if (item.Selected)
{
selected = true;


}
}
if (!selected)
{
errorMessage = "Please select the list to which your contact will be added.";
}
args.IsValid = selected;
}
}

private Contact GetContactInformation()
{
Contact contact = new Contact();


contact.EmailAddress = Server.HtmlEncode(txtEmail.Text.Trim());
contact.FirstName = Server.HtmlEncode(txtFirst.Text.Trim());
contact.LastName = Server.HtmlEncode(txtLast.Text.Trim());
foreach (ListItem item in chkListContactLists.Items)
{
if (!item.Selected) continue;
ContactOptInList contactOptInList = new ContactOptInList();
contactOptInList.ContactList = new ContactList(item.Value);
contact.ContactLists.Add(contactOptInList);
}

return contact;
}

}
add api information in web.config








3 comments:

PC-PDX.com said...

this is wothless because you didn't include the dependent class libraries.

You're also using a transitional doctype and tables for non tabular data.

Rajeev said...

this posting for expert programmer..you can get these classes from CC website, just search...

Unknown said...
This comment has been removed by the author.