public static bool DeleteContact(ConstantContactCredential credential, Contact contact) { var request = WebRequest.Create(contact.Link) as HttpWebRequest; if (request == null) { throw new WebException("Failed to create WebRequest"); } request.Credentials = credential; request.Method = "DELETE"; request.ContentType = "application/atom+xml"; // "application/x-www-form-urlencoded"; // Get response using (var webResponse = request.GetResponse() as HttpWebResponse) { if (webResponse != null) { if (webResponse.StatusCode != HttpStatusCode.OK) throw new WebException(webResponse.StatusDescription); return (webResponse.StatusCode == HttpStatusCode.OK); } } return false; }
public ContactContent(SyndicationItem item) { SyndicationContent contactContent = item.Content; if (contactContent == null) throw new ArgumentNullException(@"item"); if (String.Compare(contactContent.Type, Constants.ContactContentType, true, CultureInfo.InvariantCulture) != 0) { throw new InvalidDataException(String.Format("Expected content type {0} but encountered {1}", Constants.ContactContentType, contactContent.Type)); } XmlDictionaryReader xmlReader = ((XmlSyndicationContent)(contactContent)).GetReaderAtContent(); String elementName; Contact = new Contact(); if (item.Links.Count > 0) Contact.Link = item.Links[0].Uri.ToString(); while (xmlReader.Read()) { elementName = xmlReader.Name; // skip this node if the name is empty if (String.IsNullOrEmpty(elementName)) continue; if (elementName.Equals("Contact")) { if (xmlReader.HasAttributes) { Contact.Id = new Uri(xmlReader.GetAttribute("id")); } } else if (elementName.Equals("Status")) { Contact.Status = (ContactStatus)Enum.Parse( typeof(ContactStatus), xmlReader.ReadString().Replace(' ', '_')); } else if (elementName.Equals("EmailAddress")) { Contact.EmailAddress = xmlReader.ReadString(); } else if (elementName.Equals("EmailType")) { Contact.EmailType = (ContactEmailPreference)Enum.Parse( typeof(ContactEmailPreference), xmlReader.ReadString()); } else if (elementName.Equals("Name")) { Contact.Name = xmlReader.ReadString(); } else if (elementName.Equals("FirstName")) { Contact.FirstName = xmlReader.ReadString(); } else if (elementName.Equals("LastName")) { Contact.LastName = xmlReader.ReadString(); } else if (elementName.Equals("JobTitle")) { Contact.JobTitle = xmlReader.ReadString(); } else if (elementName.Equals("CompanyName")) { Contact.CompanyName = xmlReader.ReadString(); } else if (elementName.Equals("HomePhone")) { Contact.HomePhone = xmlReader.ReadString(); } else if (elementName.Equals("WorkPhone")) { Contact.WorkPhone = xmlReader.ReadString(); } else if (elementName.Equals("Addr1")) { Contact.Addr1 = xmlReader.ReadString(); } else if (elementName.Equals("Addr2")) { Contact.Addr2 = xmlReader.ReadString(); } else if (elementName.Equals("Addr3")) { Contact.Addr3 = xmlReader.ReadString(); } else if (elementName.Equals("City")) { Contact.City = xmlReader.ReadString(); } else if (elementName.Equals("StateCode")) { Contact.StateCode = xmlReader.ReadString(); } else if (elementName.Equals("StateName")) { Contact.StateName = xmlReader.ReadString(); } else if (elementName.Equals("CountryCode")) { Contact.CountryCode = xmlReader.ReadString(); } else if (elementName.Equals("CountryName")) { Contact.CountryName = xmlReader.ReadString(); } else if (elementName.Equals("PostalCode")) { Contact.PostalCode = xmlReader.ReadString(); } else if (elementName.Equals("SubPostalCode")) { Contact.SubPostalCode = xmlReader.ReadString(); } else if (elementName.Equals("Note")) { Contact.Note = xmlReader.ReadString(); } else if (elementName.StartsWith("CustomField")) { Int32 index = Int32.Parse(elementName.Substring(11)); Contact.CustomField[index] = xmlReader.ReadString(); } else if (elementName.Equals("OptInTime")) { Contact.OptInTime = DateTimeOffset.Parse(xmlReader.ReadString()); } else if (elementName.Equals("OptInSource")) { Contact.OptInSource = (OptInSource)Enum.Parse( typeof(OptInSource), xmlReader.ReadString()); } else if (elementName.Equals("Confirmed")) { Contact.Confirmed = Boolean.Parse(xmlReader.ReadString()); } else if (elementName.Equals("InsertTime")) { Contact.InsertTime = DateTimeOffset.Parse(xmlReader.ReadString()); } else if (elementName.Equals("LastUpdateTime")) { Contact.LastUpdateTime = DateTimeOffset.Parse(xmlReader.ReadString()); } else if (elementName.Equals("ContactList")) { if (xmlReader.HasAttributes) { var list = new ContactList(xmlReader.GetAttribute("id")); for (; xmlReader.Name.Equals("ContactList") && !xmlReader.IsStartElement(); xmlReader.Read()) { if (xmlReader.Name.Equals("OptInSource")) { list.OptInSource = (OptInSource)Enum.Parse( typeof(OptInSource), xmlReader.ReadString()); } else if (xmlReader.Name.Equals("OptInTime")) { list.OptInTime = DateTimeOffset.Parse(xmlReader.ReadString()); } } Contact.Lists.Add(list); } } else { Debug.WriteLine(String.Format("Unhandled element: {0}", elementName)); } } // while }
/// <summary> /// Initializes a new instance of the <see cref="ContactContent"/> class. /// </summary> /// <param name="contact">The contact to create syndication content for</param> public ContactContent(Contact contact) { Contact = contact; }
public static void UpdateContact(ConstantContactCredential credential, Contact contact) { var uri = new Uri(String.Format("{0}{1}", Constants.ApiEndpoint, contact.Link)); PutContact(credential, uri, contact); }
public static void CreateContact(ConstantContactCredential credential, Contact contact) { const String uriFormat = "{0}/ws/customers/{1}/contacts"; var uri = new Uri(String.Format(uriFormat, Constants.ApiEndpoint, credential.CustomerUserName)); PostContact(credential, uri, contact); }
protected static HttpStatusCode SendContact( ConstantContactCredential credential, Uri uri, String method, Contact contact) { var request = WebRequest.Create(uri) as HttpWebRequest; if (request == null) { throw new WebException("Failed to create WebRequest"); } request.Credentials = credential; request.Headers.Add("Authorization", String.Format("Basic {0}", Convert.ToBase64String(Encoding.ASCII.GetBytes(credential.Password)))); request.Method = method; request.ContentType = "application/atom+xml"; // "application/x-www-form-urlencoded"; var contactItem = new SyndicationItem { Id = (contact.Id != null) ? contact.Id.ToString() : "data:,none", Content = new ContactContent(contact) }; contactItem.Authors.Add(new SyndicationPerson(typeof(ContactsCollection).FullName)); contactItem.Summary = new TextSyndicationContent("Contact"); var atomFormatter = new Atom10ItemFormatter(contactItem); using (var memoryStream = new MemoryStream()) { var writerSettings = new XmlWriterSettings { Indent = true, IndentChars = " ", OmitXmlDeclaration = true, Encoding = new UTF8Encoding(false), }; var xmlWriter = XmlWriter.Create(memoryStream, writerSettings); if (xmlWriter == null) throw new XmlException("Failed to create XmlWriter"); atomFormatter.WriteTo(xmlWriter); xmlWriter.Flush(); memoryStream.Seek(0, SeekOrigin.Begin); byte[] data = memoryStream.ToArray(); memoryStream.Close(); Debug.WriteLine(Encoding.UTF8.GetString(data)); // Set the content length in the request headers request.ContentLength = data.Length; // Write data using (var postStream = request.GetRequestStream()) { if (data.Length > int.MaxValue) { throw new InvalidDataException( String.Format("Contact content length exceeds {0} bytes", int.MaxValue)); } postStream.Write(data, 0, data.Length); } } // Get response using (var webResponse = request.GetResponse() as HttpWebResponse) { if (webResponse == null) { throw new WebException("Failed to get HttpWebResponse"); } // Get the response stream using (var reader = new StreamReader(webResponse.GetResponseStream())) { var response = reader.ReadToEnd(); Debug.WriteLine(response); } return webResponse.StatusCode; } }
protected static void PutContact(ConstantContactCredential credential, Uri uri, Contact contact) { var statusCode = SendContact(credential, uri, "PUT", contact); if (statusCode != HttpStatusCode.NoContent) throw new WebException(statusCode.ToString()); }
protected static void PostContact(ConstantContactCredential credential, Uri uri, Contact contact) { var statusCode = SendContact(credential, uri, "POST", contact); if (!((statusCode == HttpStatusCode.Created) || (statusCode != HttpStatusCode.OK))) { throw new WebException(statusCode.ToString()); } }
protected void SubscribeUser(object sender, EventArgs e) { NewsletterSignup.Visible = false; /* var remotePost = new RemotePost { Url = "http://visitor.constantcontact.com/d.jsp" }; remotePost.Add("m", "1102557664784"); remotePost.Add("p", "oi"); remotePost.Add("ea", EmailAddressText.Text); remotePost.Post(); */ var generalInterestList = new ContactList("/ws/customers/wwfmarket/lists/1") { OptInSource = OptInSource.ACTION_BY_CONTACT, OptInTime = DateTimeOffset.Now }; try { Contact contact = ContactsCollection.GetContactByEmail( ConstantContactCredential, EmailAddressText.Text); if (contact == null) { contact = new Contact { Status = ContactStatus.Active, FirstName = FirstNameText.Text, LastName = LastNameText.Text, EmailAddress = EmailAddressText.Text, OptInSource = OptInSource.ACTION_BY_CONTACT }; contact.Lists.Add(generalInterestList); ContactsCollection.CreateContact(ConstantContactCredential, contact); ResultHtml.Text = GetLocalResourceObject("ThankYou").ToString(); } else { var generalInterestUri = generalInterestList.Link.ToLower(); if (contact.Lists.Any(list => String.Compare(list.Link, generalInterestUri, true) == 0)) { ResultHtml.Text = GetLocalResourceObject("AlreadySubscribed").ToString(); return; } contact.Lists.Add(generalInterestList); ContactsCollection.UpdateContact(ConstantContactCredential, contact); ResultHtml.Text = GetLocalResourceObject("ThankYou").ToString(); } } catch (WebException webException) { if (webException.Response != null) { var errorMessage = (new StreamReader( webException.Response.GetResponseStream())).ReadToEnd(); ResultHtml.Text = Server.HtmlEncode(String.Format("{0}: {1}{2}", webException.Status, errorMessage, Environment.NewLine)); } else { ResultHtml.Text = String.Format( GetLocalResourceObject("SubscribeErrorFormat").ToString(), webException.Message); } } ResultPanel.Visible = true; MetaRefresh.Attributes["HTTP-EQUIV"] = "refresh"; MetaRefresh.Attributes["content"] = "3;URL=" + Page.ResolveUrl("~/"); }