Salesforce Rest Api code to add contacts

First Step:

Implement Authenticaion using Client Id , Client Secret

All the below values must be setup in web.config file

string clientID = ConfigurationManager.AppSettings.Get(“sfclientid”);
string clientSecret = ConfigurationManager.AppSettings.Get(“sfclientsecret”);
string redirectURL = ConfigurationManager.AppSettings.Get(“redirectapi”);
private string code;
private TokenResponse token;

 

Authentication code :

 

private void GetToken()
{
string URI = “https://login.salesforce.com/services/oauth2/token?”;
string DATA = @”{“”object””:{“”name””:””Name””}}”;
StringBuilder body = new StringBuilder();
string code = Request.QueryString[“code”];
int totalsize = 0;

try
{

if (Session[“token”] == null)
{
body.Append(“code=” + code + “&”);
body.Append(“grant_type=authorization_code&”);
body.Append(“client_id=” + clientID + “&”);
body.Append(“client_secret=” + clientSecret + “&”);
body.Append(“redirect_uri=” + redirectURL);
string result = HttpPost(URI, body.ToString());

// Convert the JSON response into a token object
JavaScriptSerializer ser = new JavaScriptSerializer();
token = ser.Deserialize<TokenResponse>(result);
Literal1.Text += “<br/> started at ” + DateTime.Now.ToLongTimeString();

string URL = token.instance_url + “/services/data/v20.0/query?q=SELECT ID,email from Contact LIMIT ” + LIMIT_SALESFORCE_IMPORT_ROWS;

System.Net.WebRequest req = System.Net.WebRequest.Create(URL);
req.Method = “GET”;
req.Headers.Add(“Authorization: OAuth ” + token.access_token);
//System.Net.WebResponse resp = req.GetResponse();
WebResponse webResponse = req.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
Session[“token”] = token.access_token.ToString();

Session[“instanceurl”] = token.instance_url.ToString();
JObject o = JObject.Parse(response);

 

}

 

 

Post method to post values to salesforce

 

public string HttpPost(string URI, string Parameters)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
req.ContentType = “application/x-www-form-urlencoded”;
req.Method = “POST”;

// Add parameters to post
byte[] data = System.Text.Encoding.ASCII.GetBytes(Parameters);
req.ContentLength = data.Length;
System.IO.Stream os = req.GetRequestStream();
os.Write(data, 0, data.Length);
os.Close();

// Do the post and get the response.
System.Net.WebResponse resp = req.GetResponse();
if (resp == null) return null;
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}

 

public string HttpGet(string URI, string Parameters)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
req.Method = “GET”;
req.Headers.Add(“Authorization: OAuth ” + token.access_token);

System.Net.WebResponse resp = req.GetResponse();
if (resp == null) return null;
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}

 

 

Finally once the authentication is done you can use the code to post new contact

string instanceurl = Convert.ToString(Session[“instanceurl”]);
string URL = instanceurl + “/services/data/v20.0/sobjects/Contact/” + id;

System.Net.WebRequest req = System.Net.WebRequest.Create(URL);
req.Method = “PATCH”;
req.Headers.Add(“Authorization: OAuth ” + Session[“token”].ToString());
req.ContentType = “application/json”;

Contact2 con = new Contact2();

con.Title_New__c = title;

if (!city.Equals(string.Empty))
con.City_New__c = city;

if (!country.Equals(string.Empty))
con.Country_New__c = country;

if (!state.Equals(string.Empty))
con.State_New__c = state;

if (!company.Equals(string.Empty))
con.Industry_New__c = company;

if (!industry.Equals(string.Empty))
con.Industry_New__c = industry;

var ser = new JavaScriptSerializer();
var body = ser.Serialize(con);

byte[] data = System.Text.Encoding.ASCII.GetBytes(body);
req.ContentLength = data.Length;
System.IO.Stream os = req.GetRequestStream();
os.Write(data, 0, data.Length);
os.Close();

WebResponse resp;

try
{
resp = req.GetResponse();
}
catch (WebException ex)
{
resp = ex.Response;
}

 

Below is the class

 

public class Contact2
{

public string Title_New__c { get; set; }
public string Industry_New__c { get; set; }

public string City_New__c { get; set; }
public string State_New__c { get; set; }
public string Country_New__c { get; set; }
public string Department { get; set; }
public string Title { get; set; }

}

 

 

Thank you