Home → Resources → Articles

Salesforce.com Web-To-Lead C# Class

(Salesforce.com,Microsoft .NET) by Jason Skowronek on 09/24/2009

Over the years I have done numerous Salesforce.com web projects using their Web Services API's and APEX libraries. I wrote this class library to do quick and dirty web-to-lead submission without having to do clunky form redirects to their out of box HTML form handler. Includes callback handler to which you can wire-up.

The Example

void Example()
{
	WebToLead w2l = new WebToLead("YOUR_ORG_ID");
	w2l.FirstName = "First";
	w2l.LastName = "Last";
	w2l.KeyValueFields["c__custom_field"] = "My Value";
	w2l.Submit();
}

SkoNet.Salesforce.WebToLead Class

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace SkoNet.Salesforce
{
	/// <summary>
	/// This class represents the base Web Lead object in Salesforce.com.
	/// </summary>
	public class WebToLead
	{
		private bool isWebToLeadUrlBuilt;

		#region Events/Event Handlers
		/// <summary>
		/// Occurs immediately following the HttpRequest.GetResponse() method being called.
		/// </summary>
		public event SubmitWebToLeadEventHandler SubmitWebToLeadEvent;
		#endregion

		#region Accessors/Properties
		private Dictionary<string, string> parms;
		/// <summary>
		/// Dictionary <string,string> containing key/value pairs of single field values
		/// </summary>
		public Dictionary<string,string> KeyValueFields
		{
			set
			{
				parms = value;
			}
			get
			{
				return parms;
			}
		}

		private Dictionary<string, List<string>> keyPicklistFields;
		/// <summary>
		/// Dictionary <string,List<string,string>> containing key/value pairs of multi-select values
		/// </summary>
		public Dictionary<string, List<string>> KeyPicklistFields
		{
			get
			{
				return keyPicklistFields;
			}
			set
			{
				keyPicklistFields = value;
			}
		}

		private string webRequestMethod;
		/// <summary>
		/// Method to submit HttpRequest to Salesforce.com. Default is POST
		/// </summary>
		public string WebRequestMethod
		{
			set
			{
				webRequestMethod = value;
			}
			get
			{
				return webRequestMethod;
			}
		}

		private string webContentType;
		/// <summary>
		/// ContentType when submitting to Salesforce.com. Default is application/x-www-form-urlencoded
		/// </summary>
		public string WebContentType
		{
			set
			{
				webContentType = value;
			}
			get
			{
				return webContentType;
			}
		}

		private string webToLeadUrl;
		/// <summary>
		/// The Web-to-lead form action URL as outputed in the Web-to-lead HTML generation wizard.
		/// </summary>
		public string WebToLeadUrl
		{
			set
			{
				webToLeadUrl = value;
			}
			get
			{
				return webToLeadUrl;
			}
		}

		private string webToLeadData;
		/// <summary>
		/// Form data that will be submitted to Salesforce.com. Viewable only after the BuildWebToLeadUrl() method is called.
		/// </summary>
		public string WebToLeadData
		{
			get
			{
				return webToLeadData;
			}
		}

		#region Default SFDC Lead Fields (strong typed)
		private bool enableDebug;
		/// <summary>
		/// Enable debug for this request (requires debug email)
		/// </summary>
		public bool EnableDebug
		{
			set
			{
				enableDebug = value;
				parms["debug"] = value ? "1" : "0";
			}
			get
			{
				return enableDebug;
			}
		}

		private string debugEmail;
		/// <summary>
		/// If debug is enabled, the email address to send the submitted lead confirmation.
		/// </summary>
		public string DebugEmail
		{
			set
			{
				debugEmail = value;
				parms["debugEmail"] = value;
			}
			get
			{
				return debugEmail;
			}
		}

		private string recordType;
		/// <summary>
		/// Lead Record Type
		/// </summary>
		public virtual string RecordType
		{
			set
			{
				recordType = value;
				parms["recordType"] = value;
			}
			get { return recordType; }
		}

		private string organizationID;
		/// <summary>
		/// The Organization ID for the account to which leads should be posted
		/// </summary>
		public string OrganizationID
		{
			set
			{
				organizationID = value;
				parms["oid"] = value;
			}
			get { return organizationID; }
		}

		private string firstName;
		public virtual string FirstName
		{
			set
			{
				firstName = value;
				parms["first_name"] = value;
			}
			get { return firstName; }
		}

		private string lastName;
		public virtual string LastName
		{
			set
			{
				lastName = value;
				parms["last_name"] = value;
			}
			get { return lastName; }
		}

		private string email;
		public virtual string Email
		{
			set
			{
				email = value;
				parms["email"] = value;
			}
			get { return email; }
		}

		private string title;
		public virtual string Title
		{
			set
			{
				title = value;
				parms["title"] = value;
			}
			get { return title; }
		}

		private string company;
		public virtual string Company
		{
			set
			{
				company = value;
				parms["company"] = value;
			}
			get { return company; }
		}

		private string industry;
		public virtual string Industry
		{
			set
			{
				industry = value;
				parms["industry"] = value;
			}
			get { return industry; }
		}

		private string street;
		public virtual string Street
		{
			set
			{
				street = value;
				parms["street"] = value;
			}
			get { return street; }
		}

		private string city;
		public virtual string City
		{
			set
			{
				city = value;
				parms["city"] = value;
			}
			get { return city; }
		}

		private string state;
		public virtual string State
		{
			set
			{
				state = value;
				parms["state"] = value;
			}
			get { return state; }
		}

		private string postalCode;
		public virtual string PostalCode
		{
			set
			{
				postalCode = value;
				parms["zip"] = value;
			}
			get { return postalCode; }
		}

		private string country;
		public virtual string Country
		{
			set
			{
				country = value;
				parms["country"] = value;
			}
			get { return country; }
		}

		private string phone;
		public virtual string Phone
		{
			set
			{
				phone = value;
				parms["phone"] = value;
			}
			get { return phone; }
		}

		private string fax;
		public virtual string Fax
		{
			set
			{
				fax = value;
				parms["fax"] = value;
			}
			get { return fax; }
		}

		private string webSite;
		/// <summary>
		/// Web site for the lead being submitted
		/// </summary>
		public virtual string WebSite
		{
			set
			{
				webSite = value;
				parms["URL"] = value;
			}
			get { return webSite; }
		}

		private string campaignId;
		public virtual string CampaignId
		{
			set
			{
				campaignId = value;
				parms["Campaign_ID"] = value;
			}
			get { return campaignId; }
		}

		private string leadSource;
		public virtual string LeadSource
		{
			set
			{
				leadSource = value;
				parms["lead_source"] = value;
			}
			get { return leadSource; }
		}

		private string description;
		public virtual string Description
		{
			set
			{
				description = value;
				parms["description"] = value;
			}
			get { return description; }
		}
		#endregion
		#endregion

		#region Constructors
		/// <summary>
		/// Provides properties, methods, and events that pertain to submitting a Web-to-lead request in a Salesforce.com instance.
		/// </summary>
		/// <param name="oid">Organization ID of the Salesforce.com account to which the lead submission will be sent.</param>
		public WebToLead(string oid)
		{
			// initialize default salesforce fields
			organizationID = oid;
			debugEmail = String.Empty;
			enableDebug = false;
			recordType = String.Empty;
			campaignId = String.Empty;
			leadSource = String.Empty;
			
			firstName = String.Empty;
			lastName = String.Empty;
			email = String.Empty;
			title = String.Empty;
			company = String.Empty;
			industry = String.Empty;

			street = String.Empty;
			city = String.Empty;
			state = String.Empty;
			postalCode = String.Empty;
			country = String.Empty;
			phone = String.Empty;
			fax = String.Empty;
			
			description = String.Empty;
			webSite = String.Empty;
			
			parms = new Dictionary<string, string>();
			keyPicklistFields = new Dictionary<string, List<string>>();

			// initialize other class members
			isWebToLeadUrlBuilt = false;
			webToLeadUrl = "https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8"; // default
			webRequestMethod = "POST"; // default request method
			webContentType = "application/x-www-form-urlencoded"; // default content type
		}

		public WebToLead() : this(String.Empty) { }
		#endregion

		/// <summary>
		/// Generate the URL and POST Data that will be used to submit the request to salesforce.com
		/// </summary>
		public virtual void BuildWebToLeadUrl()
		{
			const string FORMAT = "&{0}={1}";
			StringBuilder query = new StringBuilder();

			// pull single select values
			foreach (string key in parms.Keys)
			{
				string val = (string)parms[key];
				val = HttpUtility.UrlEncode(val);
				string keyName = String.Format(FORMAT, key, val);
				query.Append(keyName);
			}

			// pull multiselect values
			foreach (string key in keyPicklistFields.Keys)
			{
				List<string> vals = (List<string>)keyPicklistFields[key];
				foreach (string val1 in vals)
				{
					if (!String.IsNullOrEmpty(val1))
					{
						string val = val1;
						val = HttpUtility.UrlEncode(val1);
						string keyName = String.Format(FORMAT, key, val);
						query.Append(keyName);
					}
				}
			}

			webToLeadData = query.ToString();
			isWebToLeadUrlBuilt = true;
		}

		/// <summary>
		/// Submit the Web to Lead request to Salesforce.com
		/// </summary>
		public virtual void Submit()
		{
			// make sure submit data has been generated
			if (!isWebToLeadUrlBuilt) BuildWebToLeadUrl();

			// verify required properties are set
			if (String.IsNullOrEmpty(organizationID) || String.IsNullOrEmpty(webToLeadUrl))
			{
				throw new SalesforceException("You must specify an organization ID and a web to lead URL before you can submit a lead to Salesforce.");
			}

			// encode data and convert to byte array to send
			UTF8Encoding encoding = new UTF8Encoding();
			byte[] byteArray = encoding.GetBytes(webToLeadData);

			// Create HttpWebRequest
			HttpWebRequest reqSF = (HttpWebRequest)WebRequest.Create(webToLeadUrl);
			reqSF.Method = webRequestMethod;
			reqSF.ContentType = webContentType;
			reqSF.ContentLength = webToLeadData.Length;

			// Post the data stream to Salesforce
			Stream requestStream = reqSF.GetRequestStream();
			requestStream.Write(byteArray, 0, byteArray.Length);
			requestStream.Close();

			//Get the response data stream from Salesforce
			HttpWebResponse respSF = (HttpWebResponse)reqSF.GetResponse();
			// raise the event
			if (SubmitWebToLeadEvent != null)
			{
				SubmitWebToLeadEvent(this, new SubmitWebToLeadEventArgs(respSF));
			}
			respSF.Close();
			respSF = null;
			reqSF = null;
		}
	}

	/// <summary>
	/// Represents the method that will handle a WebToLeadSubmit event that has WebToLeadSubmitEventArgs data.
	/// </summary>
	/// <param name="sender">Object</param>
	/// <param name="e">WebToLeadSubmitEventArgs</param>
	public delegate void SubmitWebToLeadEventHandler(object sender, SubmitWebToLeadEventArgs e);

	/// <summary>
	/// Provides data for the web to lead submission of the WebToLead class.
	/// </summary>
	public class SubmitWebToLeadEventArgs
	{
		private HttpWebResponse response;
		public HttpWebResponse Response
		{
			set
			{
				response = value;
			}
			get
			{
				return response;
			}
		}

		public SubmitWebToLeadEventArgs(HttpWebResponse input)
		{
			response = input;
		}
	}
}

Comments (7)

Mike

6/3/2010 6:54:40 PM
I am not that proficient with .NET, but I was wondering if you might be able to help provide a little more info on how to set this up. I'm currently calling the class with the following, but I'm not getting leads into SF. Is there a simple example page of how this might be achieved? This what I'm calling as of now: SkoNet.Salesforce.WebToLead xLead = new SkoNet.Salesforce.WebToLead(); xLead.SubmitWebToLeadEvent += new SkoNet.Salesforce.SubmitWebToLeadEventHandler(xLead_SubmitWebToLeadEvent); xLead.OrganizationID = "XXXXXXXXXXXXX"; xLead.FirstName = first_name.Text; xLead.LastName = last_name.Text; xLead.Submit();

Mike

6/3/2010 6:57:00 PM
Would you have a basic sample C# app to review? I'm not having much luck at this time getting the leads into SF.

Jason

6/3/2010 7:23:11 PM
Thanks for the post. I haven't actually posted any sort of example of it's usage. I can see if I can round something up. It's pretty old code too, so it may need to be modified for the new API's. If I can help more let me know. Take care.

M

1/9/2012 10:24:12 PM
You don't have an example of this working or a simple way to call the code?

Jason Skowronek

1/9/2012 10:31:26 PM
I'll update this with a working example when I have a chance.

M

1/12/2012 10:19:57 PM
Awesome, Thanks :D

Jason

1/12/2012 10:32:02 PM
You're welcome. Keep in mind, this class is fairly old. You may find better ones in the developer samples nowadays.
Leave a comment
Name *
Email *
Homepage
Comment

Recommend

UltraEdit

 

Nero Sale 150x150 

System Mechanic 

SkoNet provides comprehensive digital consulting services such as: web development, applications development, database design and architecture, business process management, customer relationship management, and many others that help businesses of every size, industry, and geography meet the complex challenge of managing and sharing information on the web. Our skills and expertise in online systems allow us to help customers build applications ranging from simple, single-page web sites to robust enterprise systems.

Online Backup, Ektron Consulting, Ektron Programmer, Ektron Developer, Ektron Partner Utah, Ektron Partner, Ektron Architect, Ektron Hosting, Salesforce.com Consultant Utah, Salesforce.com Partner Utah, Salesforce.com Partner, Salesforce.com Programmer, Salesforce.com Architect, Salesforce.com APEX Programmer