I am trying to call Salesforce Parnter wsdl to Create Leads to their system through my c# code.
but its giving me error:
Cannot implicitly convert type Contact[]' to 'sforce.sObject'
private string userID = "sasxxasasas#saasforce.in";
private string password = "sadwdasdasdasdsadasdsxzdddw";
private DateTime _nextLoginTime;
private string _sessionId;
string url="valueleads.in/pushleads/websvc/cigna/wsdl.xml";
SforceService binding;
private void getSessionInfo()
{
sforce.SforceService partnerService = new sforce.SforceService();
sforce.LoginResult lr = new sforce.LoginResult();
lr = partnerService.login(userID, password);
_sessionId = lr.sessionId;
Session["_sessionId"] = lr.sessionId;
Session["_serverUrl"] = lr.serverUrl;
Session["_nextLoginTime"] = DateTime.Now;
binding.SessionHeaderValue = new sforce.SessionHeader();
binding.SessionHeaderValue.sessionId = _sessionId;
binding.Url = lr.serverUrl;
}
public bool IsConnected()
{
bool blnResult = false;
if (!string.IsNullOrEmpty(_sessionId) & _sessionId != null)
{
if (DateTime.Now > _nextLoginTime)
blnResult = false;
else
blnResult = true;
}
else
blnResult = false;
return blnResult;
}
public void create()
{
if (!IsConnected())
{
getSessionInfo();
}
binding = new SforceService();
Contact contact=new Contact();
contact.fname="Eric";
contact.lname="Peter";
contact.mobile="9898989889";
Contact[] contacts = { contact };
string result;
sforce.SaveResult[] createResults = binding.create(new sObject[] { contacts });
if (createResults[0].success)
{
result = createResults[0].id;
}
else
{
result = createResults[0].errors[0].message;
}
Response.Write(result);
}
}
public class Contact
{
public String fname { get; set; }
public String lname { get; set; }
public String mobile { get; set; }
}
}
please help, very much new to this salesforce API.
You need to create an array of SObjects, not contacts, so do
sforce.sObject[] contacts = { contact };
string result;
sforce.SaveResult[] createResults = binding.create(contacts);
Related
I'm currently trying to scrape a cannabis strain database as it is no longer being maintained. I seem to be running into an issue where table rows are skipped in my logic but it really doesn't make sense, it's like a break is being called when I'm iterating through the //tr elements of the table that is storing the chemical reports.
Is it something like the δ α symbols in the next row. I've tried regex replacing them out to now luck. Any help would be appreciated all code is in a single class console app.
Issue is in the table.ChildNodes not iterating all the way through. Located in the ParseChemical() method.
Sample Page: http://ocpdb.pythonanywhere.com/ocpdb/420/
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.Design;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Http;
using System.Reflection.Emit;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using HtmlAgilityPack;
using Microsoft.VisualBasic.CompilerServices;
namespace CScrape
{
class Program
{
private static readonly HttpClient Client = new HttpClient();
private static readonly string BaseUri = "http://ocpdb.pythonanywhere.com/ocpdb/";
private static int _startId = 420;
private static int _endId = 1519;
private static List<Lab> _labs = new List<Lab>();
private static List<ChemicalItem> _chemicalItems = new List<ChemicalItem>();
private static List<UnitOfMeasure> _uoms = new List<UnitOfMeasure>();
private static List<Strain> _strains = new List<Strain>();
static void Main(string[] args)
{
Client.DefaultRequestHeaders.Accept.Clear();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13;
_uoms.AddRange(GetUoms());
for (var i = _startId; i <= _endId; i++)
{
var result = GetUri($"{BaseUri}{i}").Result;
_strains.Add(ParseChemical(result));
}
}
private static long AddChemicalItem(ChemicalItem item)
{
if (ChemicalExists(item.Symbol))
return _chemicalItems.FirstOrDefault(ci => ci.Symbol == item.Symbol)?.Id ?? -1;
item.Id = _chemicalItems.Count + 1;
_chemicalItems.Add(item);
return item.Id;
}
private static void UpdateChemicalItem(ChemicalItem item)
{
if (!ChemicalExists(item.Symbol)) return;
var index = _chemicalItems.IndexOf(item);
if (!(index >= 0)) return;
_chemicalItems.RemoveAt(index);
AddChemicalItem(item);
}
private static long AddLab(Lab lab)
{
if (LabExists(lab.Name))
return _labs.FirstOrDefault(l => l.Name == lab.Name)?.Id ?? -1;
lab.Id = _labs.Count + 1;
_labs.Add(lab);
return lab.Id;
}
private static async Task<string> GetUri(string uri)
{
var response = await Client.GetByteArrayAsync(uri);
return Encoding.UTF8.GetString(response, 0, response.Length - 1);
}
private static Strain ParseChemical(string html)
{
html = Regex.Replace(html, #"Δ", "Delta");
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
var strain = new Strain();
strain.Reports ??= new List<ChemicalReport>();
try
{
strain.Name = htmlDoc.DocumentNode.SelectSingleNode("/html/body/div/div[1]/div[1]/h3/b").InnerText;
}
catch (Exception e)
{
// TODO: DOcument Exception
Console.WriteLine(e.Message);
}
if (string.IsNullOrWhiteSpace(strain.Name)) return null;
try
{
var ocpId = htmlDoc.DocumentNode.SelectSingleNode("/html/body/div/div[1]/div[2]/p/b/text()[1]");
strain.OcpId = SanitizeHtml(ocpId.InnerText).Split(':')[1];
}
catch (Exception e)
{
// TODO: Document Exception
Console.WriteLine(e.Message);
}
if (string.IsNullOrWhiteSpace(strain.OcpId)) return null;
try
{
var date = htmlDoc.DocumentNode.SelectSingleNode("/html/body/div/div[1]/div[2]/p/text()");
}
catch (Exception e)
{
// TODO: Document Exception
Console.WriteLine(e.Message);
}
var chemReport = new ChemicalReport();
chemReport.Items ??= new List<ReportItem>();
try
{
var table = htmlDoc.DocumentNode.SelectSingleNode("/html/body/div/div[2]/div[1]/table/tbody");
var children = table.ChildNodes.ToList();
// On the sample page there are 200 children here
// However it only interates through the first few and then just breaks out of the loop
foreach (var child in children)
{
var name = child.Name;
if (child.Name == "tr")
{
var infos = child.SelectNodes("th|td");
foreach (var info in infos)
{
if(string.IsNullOrWhiteSpace(info.InnerText)) continue;
if (info.InnerText.Contains("Report")) continue;
if (double.TryParse(info.InnerText, out var isNumber))
{
var last = chemReport.Items.LastOrDefault();
if (last == null) continue;
if (last.Value <= 0.0000) last.Value = isNumber;
else
{
var further = chemReport.Items.ToArray()[chemReport.Items.Count - 2];
if (further.Value <= 0.0000)
further.Value = isNumber;
}
continue;
}
var _ = new ChemicalItem
{
Name = info.InnerText,
Symbol = info.InnerText
};
_.Id = AddChemicalItem(_);
var report = new ReportItem
{
Chemical = _,
ChemicalItemId = _.Id,
UnitOfMeasureId = 1,
UoM = GetUoms()[0]
};
chemReport.Items.Add(report);
}
}
}
strain.Reports.Add(chemReport);
}
catch (Exception e)
{
// TODO: Document exception
Console.Write(e.Message);
}
return strain;
}
private static List<UnitOfMeasure> GetUoms()
{
return new List<UnitOfMeasure>
{
new UnitOfMeasure {Name = "Milligrams per Gram", Symbol = "mg/g"},
new UnitOfMeasure {Name = "Percent", Symbol = "%"}
};
}
private static string SanitizeHtml(string text, string replacement = "")
{
return Regex.Replace(text, #"<[^>]+>| |α|\n|\t", replacement);
}
private static string GetLabName(string[] split)
{
var strip = split[0].Split(':')[1];
for(var i = 1; i < split.Length - 2; i ++)
{
if (string.IsNullOrWhiteSpace(split[i])) break;
strip += $" {split[i]}";
}
return strip;
}
private static string GetSampleId(string[] split)
{
var found = false;
foreach (var item in split)
{
if (found)
return item.Split(':')[1];
if (item == "Sample") found = true;
}
return "NA";
}
private static bool LabExists(string name)
{
return _labs.Any(lab => lab.Name == name);
}
private static bool ChemicalExists(string name)
{
return _chemicalItems.Any(ci => ci.Symbol == name);
}
private static ReportItem GetReportItem(string text)
{
if (string.IsNullOrWhiteSpace(text)) return null;
ReportItem ri = null;
try
{
var clean = SanitizeHtml(text);
var check = 0;
var split = clean.Split(':');
var label = split[0];
if (string.IsNullOrWhiteSpace(label)) return null;
if (double.TryParse(label, out var invalidType)) return null;
var val = string.Empty;
if (split.Length == 1)
{
if (split[0].Contains("Total"))
{
Regex re = new Regex(#"([a-zA-Z]+)(\d+)");
Match result = re.Match(split[0]);
label = result.Groups[1].Value;
val = result.Groups[2].Value;
}
}
if(split.Length > 1)
val = split[1];
if (!ChemicalExists(label)) AddChemicalItem(new ChemicalItem {Id = _chemicalItems.Count + 1,Symbol = label});
ri = new ReportItem();
ri.Chemical = _chemicalItems.FirstOrDefault(ci => ci.Symbol == label);
ri.UoM = val.Contains("%")
? _uoms.FirstOrDefault(uom => uom.Symbol == "%")
: _uoms.FirstOrDefault(uom => uom.Symbol == "mg/g");
if (string.IsNullOrWhiteSpace(val)) return ri;
var value = val.Contains("%") ? split[1].Substring(0, val.Length - 1) : val;
ri.Value = Convert.ToDouble(value);
}
catch (Exception e)
{
// TODO: Document Exception
Console.WriteLine(e.Message);
}
return ri;
}
//private static ChemicalItem GetChemicalItem(string text)
//{
//}
public class Strain
{
public long Id { get; set; }
public string Name { get; set; }
public DateTime Created { get; set; }
public string OcpId { get; set; }
public bool IsHidden { get; set; } = false;
public virtual ICollection<ChemicalReport> Reports { get; set; }
}
public class Lab
{
public long Id { get; set; }
public string Name { get; set; }
public virtual ICollection<ChemicalReport> Reports { get; set; }
}
public class ChemicalReport
{
public long Id { get; set; }
[ForeignKey("Lab")]
public long LabId { get; set; }
public virtual Lab Lab { get; set; }
public string SampleId { get; set; }
public DateTime Created { get; set; }
public virtual ICollection<ReportItem> Items { get; set; }
[ForeignKey("Strain")]
public long StrainId { get; set; }
public virtual Strain Strain { get; set; }
}
public class ChemicalItem
{
public long Id { get; set; }
public string Name { get; set; }
public string Symbol { get; set; }
}
public class ReportItem
{
public long Id { get; set; }
[ForeignKey("Chemical")]
public long ChemicalItemId { get; set; }
public virtual ChemicalItem Chemical { get; set; }
public double Value { get; set; }
[ForeignKey("UoM")]
public long UnitOfMeasureId { get; set; }
public virtual UnitOfMeasure UoM { get; set; }
}
public class UnitOfMeasure
{
public long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Symbol { get; set; }
}
}
}
Hello I have a 'RestrictAccessController' That looks like this
public class RestrictAccessController : Controller
{
private PIC_Program_1_0Context db = new PIC_Program_1_0Context();
public ActionResult Index()
{
return View ();
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple=true)]
public class RestrictAccessAttribute : ActionFilterAttribute
{
private PIC_Program_1_0Context db = new PIC_Program_1_0Context();
public AccessRestrictions restriction { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
// here's where we check that the current action is allowed by the current user
if (!IGT.canAccess(IGT.userId, restriction, false))
{
string url = IGT.baseUrl+"/Home/NotAllowed";
string msg = "This page requires " + IGT.DisplayEnum(restriction) + " access";
filterContext.Result = new RedirectResult("~/Home/NotAllowed?msg="+HttpUtility.HtmlEncode(msg));
}
}
And a Config model that looks like this
public enum AccessRestrictions
{
[Display(Name = "Disposal Orders")]
ModifyDisposalOrder,
[Display(Name = "Admin")]
Admin
}
public class userAccess
{
[Key]
public int ID { get; set; }
public AccessRestrictions restriction { get; set; }
public bool allow { get; set; }
public int userID { get; set; }
}
public class configDetails
{
public int ID {get; set;}
public string Name {get; set;}
public string Value {get;set;}
public bool deleted {get;set;}
public DateTime updateTime { get; set; }
}
public class Config
{
public int ID { get; set; }
[Display(Name = "Configuration Date")]
public DateTime TargetDate { get; set; }
[Display(Name = "Enable Access Restrictions")]
public bool restrictAccess { get; set; }
}
What I want to do is edit what my 'ChangeStatus' dropdown looks like based on whether they have the Admin access restriction or not. Here is the controller method that I want to edit
[RestrictAccess(restriction = AccessRestrictions.ModifyDisposalOrder)]
public ActionResult ChangeStatus(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DisposalOrder disposalOrder = db.disposalOrders.Find(id);
if (disposalOrder == null)
{
return HttpNotFound();
}
switch (disposalOrder.Status)
{
case DOStatus.Pending:
ViewBag.statusList = new List<Object>
{
new {value = DOStatus.Pending, text = "Pending"},
new {value = DOStatus.Disposed, text = "Disposed" }
};
break;
case DOStatus.Disposed:
// if(restriction = AccessRestrictions.ModifyDisposalOrder)
ViewBag.statusList = new List<Object>
{
new {value = DOStatus.Pending, text = "Pending"},
new {value = DOStatus.Disposed, text = "Disposed" }
};
//else
//{
// new { value = DOStatus.Disposed, text = "Disposed" }
// };
break;
};
return View(disposalOrder);
}
Here is my Startup file
public class LdapAuthentication
{
private string _adUser = ConfigurationManager.AppSettings["ADUserName"];
private string _adPW = ConfigurationManager.AppSettings["ADPassword"];
private string _domain = ConfigurationManager.AppSettings["ADDomain"];
public LdapAuthentication() {
}
public string authenticate(string username, string pwd)
{
using (var context = new PrincipalContext(ContextType.Domain, _domain, _adUser, _adPW)) {
//Username and password for authentication.
if (context.ValidateCredentials(username, pwd)) {
UserPrincipal user = UserPrincipal.FindByIdentity(context, username);
Internal internalUser = new Internal {
UserName = user.SamAccountName,
ContactName = user.DisplayName,
Email = user.UserPrincipalName
};
//Search if the user account already exists in the database
PIC_Program_1_0Context db = new PIC_Program_1_0Context();
Internal existing = db.Internals.Where(x => x.UserName == user.SamAccountName).FirstOrDefault();
// If it does not, create a new user account
if (existing == null) {
// add a new Internal entry for this user
existing = new Internal {
UserName = user.SamAccountName,
ContactName = user.DisplayName,
Email = user.UserPrincipalName
};
db.Internals.Add(existing);
db.SaveChanges();
// If it does exist, but some of the data does not match, update the data
} else if(existing != internalUser) {
existing.ContactName = internalUser.ContactName;
existing.Email = internalUser.Email;
db.SaveChanges();
}
return user.SamAccountName;
} else {
return null;
}
}
}
public UserPrincipal getUserPrincipal(string username)
{
using (var context = new PrincipalContext(ContextType.Domain, _domain, _adUser, _adPW))
{
return UserPrincipal.FindByIdentity(context, username);
}
}
Is it possible for me to accomplish this?
Ok, I think I understand your question now. You need to access the User's claims. MVC Controllers have this, half way, built in.
if (User.HasClaim("ClaimNameHere", "Admin"))
{
}
Solved by adding
if (IGT.canAccess(IGT.userId, AccessRestrictions.Admin, false))
these is my code for setting session object. i want to use that object to get the infomation of login user. but i am unable to do that i get the error 'Input String is not in correct format'. i need help here to know how to create an object & get values from my session object
public UserLoginDetails LoggedUserDetails
{
set { Session["loggeduserdetails"] = value; }
get
{
if (Session["loggeduserdetails"] == null)
{
if (Session["username"] == null)
{
Response.Redirect("../Authentication/Login.aspx");
}
if (Session["password"] == null)
{
Response.Redirect("../Authentication/Login.aspx");
}
DAL.LoginHistoryDAL LoginDAL = new DAL.LoginHistoryDAL();
DataSet Ds = LoginDAL.AuthenticateUser(Session["username"].ToString(), EncryptionUtility.Encrypt(Session["password"].ToString()));
UserLoginDetails ULD = new UserLoginDetails();
if (Ds.Tables[0].Rows.Count > 0)
{
// Populating UserObj
bool IsAdmin = false;
bool IsMasterAdmin = false;
if (Ds.Tables[0].Rows[0]["IsAdmin"].ToString() == "1")
{
IsAdmin = true;
}
else
{
IsAdmin = false;
}
if (Ds.Tables[0].Rows[0]["IsMasterAdmin"].ToString() == "1")
{
IsMasterAdmin = true;
}
else
{
IsMasterAdmin = false;
}
ULD = new UserLoginDetails();
ULD.UserId = int.Parse(Ds.Tables[0].Rows[0]["UserId"].ToString());
ULD.IsAdmin = IsAdmin;
ULD.IsMasterAdmin = IsMasterAdmin;
ULD.UserName = Ds.Tables[0].Rows[0]["FullName"].ToString();
ULD.LocationID = int.Parse(Ds.Tables[0].Rows[0]["LocationID"].ToString());
ULD.FullName = Ds.Tables[0].Rows[0]["FullName"].ToString();
ULD.StatusId = int.Parse(Ds.Tables[0].Rows[0]["StatusId"].ToString());
ULD.Email = Ds.Tables[0].Rows[0]["Email"].ToString();
ULD.CellNo = Ds.Tables[0].Rows[0]["Cell"].ToString();
ULD.CityId = int.Parse(Ds.Tables[0].Rows[0]["CityID"].ToString());
ULD.StateId = int.Parse(Ds.Tables[0].Rows[0]["StateId"].ToString());
ULD.CountryId = int.Parse(Ds.Tables[0].Rows[0]["CountryID"].ToString());
}
Session["loggeduserdetails"] = ULD;
}
return (UserLoginDetails)Session["loggeduserdetails"];
}
}
}
public class UserLoginDetails
{
public int UserId = 0;
public bool IsAdmin = false;
public bool IsMasterAdmin = false;
public string UserName = string.Empty;
public int LocationID = 0;
public string FullName = string.Empty;
public int StatusId = 0;
public string Email = string.Empty;
public string CellNo = string.Empty;
public int CityId = 0;
public int StateId = 0;
public int CountryId = 0;
}
Looks like one of the pieces of data you expect to be a numeric value isn't.
I.e. UserId, or CityID isn't a numeric value or any other.
I would have a look at one of the following lines of code:
ULD.UserId = int.Parse(Ds.Tables[0].Rows[0]["UserId"].ToString());
ULD.LocationID = int.Parse(Ds.Tables[0].Rows[0]["LocationID"].ToString());
ULD.StatusId = int.Parse(Ds.Tables[0].Rows[0]["StatusId"].ToString());
ULD.CityId = int.Parse(Ds.Tables[0].Rows[0]["CityID"].ToString());
ULD.StateId = int.Parse(Ds.Tables[0].Rows[0]["StateId"].ToString());
ULD.CountryId = int.Parse(Ds.Tables[0].Rows[0]["CountryID"].ToString());
I'm using the official version 2 of the Constant Contact .net-sdk found here.
I've been unable to find methods for the following:
Creating a Contact List
Adding a contact to a Contact List
Removing a contact from a Contact List
Adding multiple contacts to a Contact List
Creating an Email Campaign
These features clearly exist in v2 of the API found here, but seem missing from the SDK.
Any help in accessing this functionality is appreciated.
Create Contact.
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "<Replace with your oAuth Token>");
ContactObject cont = new ContactObject
{
first_name = "Deepu",
last_name = "Madhusoodanan"
};
var email_addresses = new List<EmailAddress>
{
new EmailAddress{email_address = "deepumi1#gmail.com"}
};
cont.email_addresses = email_addresses;
cont.lists = new List<List>
{
new List {id = "<Replace with your List Id>"}
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(cont);
string MessageType = "application/json";
using (var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, "https://api.constantcontact.com/v2/contacts?api_key=<Replace with your API key>"))
{
request.Headers.Add("Accept", MessageType);
request.Content = new StringContent(json);
request.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(MessageType);
using (var response = await client.SendAsync(request).ConfigureAwait(false))
{
string responseXml = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var code = response.StatusCode;
}
request.Content.Dispose();
}
}
}
catch (Exception exp)
{
//log exception here
}
/*Model class*/
public class Address
{
public string address_type { get; set; }
public string city { get; set; }
public string country_code { get; set; }
public string line1 { get; set; }
public string line2 { get; set; }
public string line3 { get; set; }
public string postal_code { get; set; }
public string state_code { get; set; }
public string sub_postal_code { get; set; }
}
public class List
{
public string id { get; set; }
}
public class EmailAddress
{
public string email_address { get; set; }
}
public class ContactObject
{
public List<Address> addresses { get; set; }
public List<List> lists { get; set; }
public string cell_phone { get; set; }
public string company_name { get; set; }
public bool confirmed { get; set; }
public List<EmailAddress> email_addresses { get; set; }
public string fax { get; set; }
public string first_name { get; set; }
public string home_phone { get; set; }
public string job_title { get; set; }
public string last_name { get; set; }
public string middle_name { get; set; }
public string prefix_name { get; set; }
public string work_phone { get; set; }
}
Note : You have to replace oAuth token, API key and List id.
Delete method based on the api document.(http://developer.constantcontact.com/docs/contacts-api/contacts-resource.html?method=DELETE)
Note : I have not tested the delete method yet.
private async Task<string> DeleteContact(string contactId)
{
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "<Replace with your oAuth Token>");
using (var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Delete, "https://api.constantcontact.com/v2/contacts/" + contactId + "?api_key=<Replace with your API key>"))
{
using (var response = await client.SendAsync(request).ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
}
}
}
catch (Exception exp)
{
//log exp here
}
return string.Empty;
}
Here is my solution for adding a contact. What I did was combine the code that Deepu provided with the Constant Contact API v2. I also had to remove async and await references because they are incompatible with VS2010. I have not tried DELETE yet...
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Http;
using CTCT.Components.Contacts;
using System.Net.Http.Headers;
/// <summary>
/// Constant Contact Helper Class for POST, PUT, and DELETE
/// </summary>
public class ConstantContactHelper
{
private string _accessToken = ConfigurationManager.AppSettings["ccAccessToken"];
private Dictionary<string, System.Net.Http.HttpMethod> requestDict = new Dictionary<string, System.Net.Http.HttpMethod> {
{"GET", HttpMethod.Get},
{"POST", HttpMethod.Post},
{"PUT", HttpMethod.Put},
{"DELETE", HttpMethod.Delete}
};
private System.Net.Http.HttpMethod requestMethod = null;
private Dictionary<string, ConstantContactURI> uriDict = new Dictionary<string, ConstantContactURI> {
{"AddContact", new ConstantContactURI("contacts")},
{"AddContactList", new ConstantContactURI("lists")},
{"AddEmailCampaign", new ConstantContactURI("campaigns")},
};
private ConstantContactURI URI_Handler = new ConstantContactURI();
private ContactRequestBody RequestBody = new ContactRequestBody();
private const string messageType = "application/json";
public string jsonRequest = null;
public string responseXml = null;
public string status_code = null;
public ConstantContactHelper() {}
public ConstantContactHelper(string methodKey, string uriKey, string firstName, string lastName, string emailAddress, string listId)
{
this.requestMethod = this.requestDict[methodKey];
this.URI_Handler = this.uriDict[uriKey];
this.RequestBody = new ContactRequestBody(firstName, lastName, emailAddress, listId);
}
// Return Response as a string
public void TryRequest()
{
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this._accessToken);
var json = Newtonsoft.Json.JsonConvert.SerializeObject(this.RequestBody.contact);
this.jsonRequest = json;
using (var request = new HttpRequestMessage(HttpMethod.Post, this.URI_Handler.fullURI))
{
request.Headers.Add("Accept", messageType);
request.Content = new StringContent(json);
request.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(messageType);
using (var response = client.SendAsync(request))
{
this.responseXml = response.Result.Content.ReadAsStreamAsync().ConfigureAwait(false).ToString();
this.status_code = response.Status.ToString();
}
request.Content.Dispose();
}
}
}
catch(Exception exp)
{
// Handle Exception
this.responseXml = "Unhandled exception: " + exp.ToString();
}
}
}
public class ConstantContactURI
{
private const string baseURI = "https://api.constantcontact.com/v2/";
private const string queryPrefix = "?api_key=";
private string _apiKey = ConfigurationManager.AppSettings["ccApiKey"];
public string fullURI = null;
public ConstantContactURI() {}
public ConstantContactURI(string specificPath)
{
this.fullURI = baseURI + specificPath + queryPrefix + _apiKey;
}
}
public class ContactRequestBody
{
public Contact contact = new Contact();
private List<EmailAddress> email_addresses = new List<EmailAddress>()
{
new EmailAddress{
EmailAddr = "",
Status = Status.Active,
ConfirmStatus = ConfirmStatus.NoConfirmationRequired
}
};
private List<ContactList> lists = new List<ContactList>()
{
new ContactList {Id = ""}
};
public ContactRequestBody() { }
public ContactRequestBody(string firstName, string lastName, string emailAddress, string listId)
{
this.contact.FirstName = firstName;
this.contact.LastName = lastName;
this.email_addresses[0].EmailAddr = emailAddress;
this.contact.EmailAddresses = this.email_addresses;
this.lists[0].Id = listId;
this.contact.Lists = this.lists;
}
}
An Example call from an aspx.cs page looks like this:
ConstantContactHelper requestHelper = new ConstantContactHelper("POST", "AddContact", firstName.Text, lastName.Text, emailBox.Text, listId);
requestHelper.TryRequest();
lbTest.Text = requestHelper.jsonRequest + ", status code:" + requestHelper.status_code + ", xml:" + requestHelper.responseXml;
I am trying to build a combo list for a program to fill the combobox with a list of applications. it keeps throwing up "Cannot bind to the new display member. Parameter name: newDisplayMember"
private void BuildComboList()
{
Applicant defaultApplicant = new Applicant();
applicationList = defaultApplicant.GetList();
applicantList.DataSource = applicationList;
applicantList.DisplayMember = "DisplayName";
applicantList.ValueMember = "DisplayValue";
}
Applicant Class
public class Applicant
{
//Members
private int applicant_ID;
private string applicant_fname;
private string applicant_lname;
private string applicant_phone;
private string applicant_address1;
private string applicant_address2;
private string applicant_city;
private string applicant_state;
private string applicant_zip;
private string applicant_email;
//properties
public int Applicant_ID
{
get { return applicant_ID; }
set { applicant_ID = value; }
}
public string Applicant_fname
{
get { return applicant_fname; }
set { applicant_fname = value; }
}
public string Applicant_lname
{
get { return applicant_lname; }
set { applicant_lname = value; }
}
public string Applicant_phone
{
get { return applicant_phone; }
set { applicant_phone = value; }
}
public string Applicant_address1
{
get { return applicant_address1; }
set { applicant_address1 = value; }
}
public string Applicant_address2
{
get { return applicant_address2; }
set { applicant_address2 = value; }
}
public string Applicant_city
{
get { return applicant_city; }
set { applicant_city = value; }
}
public string Applicant_state
{
get { return applicant_state; }
set { applicant_state = value; }
}
public string Applicant_zip
{
get { return applicant_zip; }
set { applicant_zip = value; }
}
public string Applicant_email
{
get { return applicant_email; }
set { applicant_email = value; }
}
//Constructors
private void DefaultValues()
{
applicant_ID = 0;
applicant_fname = "";
applicant_lname = "";
applicant_phone = "";
applicant_address1 = "";
applicant_address2 = "";
applicant_city = "";
applicant_state = "";
applicant_zip = "";
applicant_email = "";
}
private void Rec2Members(ApplicantRecord record)//defined in ApplicantDL
{
applicant_ID = record.applicant_ID;
applicant_fname = record.applicant_fname;
applicant_lname = record.applicant_lname;
applicant_phone = record.applicant_phone;
applicant_address1 = record.applicant_address1;
applicant_address2 = record.applicant_address2;
applicant_city = record.applicant_city;
applicant_state = record.applicant_state;
applicant_zip = record.applicant_zip;
applicant_email = record.applicant_email;
}
public ApplicantRecord ToRecord()
{
ApplicantRecord record = new ApplicantRecord();
record.applicant_ID = applicant_ID;
record.applicant_fname = applicant_fname;
record.applicant_lname = applicant_lname;
record.applicant_phone = applicant_phone;
record.applicant_address1 = applicant_address1;
record.applicant_address2 = applicant_address2;
record.applicant_city = applicant_city;
record.applicant_state = applicant_state;
record.applicant_zip = applicant_zip;
record.applicant_email = applicant_email;
return record;
}
public List<ApplicantRecord> GetList()
{
return Approval_Form.ApplicantRecord.ApplicantDL.GetList();
}
public void Insert()
{
applicant_ID = Approval_Form.ApplicantRecord.ApplicantDL.Insert(applicant_fname, applicant_lname, applicant_phone, applicant_address1, applicant_address2, applicant_city, applicant_state, applicant_zip, applicant_email);
}
public void Select(int applicant_ID)
{
ApplicantRecord record = Approval_Form.ApplicantRecord.ApplicantDL.Select(applicant_ID);
Rec2Members(record);
}
public void Update()
{
if (applicant_ID != 0)
{
Approval_Form.ApplicantRecord.ApplicantDL.Update(applicant_ID, applicant_fname, applicant_lname, applicant_phone, applicant_address1, applicant_address2, applicant_city, applicant_state, applicant_zip, applicant_email);
}
}
}
I think it should be:
private void BuildComboList()
{
Applicant defaultApplicant = new Applicant();
applicationList = defaultApplicant.GetList();
applicantList.DataSource = applicationList;
applicantList.DisplayMember = "Applicant_fname";
applicantList.ValueMember = "Applicant_ID";
}
You can change the applicant class further as follows:
Add two properties.
public string DisplayName
{
get { return (applicant_fname + " " + applicant_lname; }
}
public string DisplayValue
{
get { return (applicant_ID.ToString(); }
}
Keep data binding as:
private void BuildComboList()
{
Applicant defaultApplicant = new Applicant();
applicationList = defaultApplicant.GetList();
applicantList.DataSource = applicationList;
applicantList.DisplayMember = "DisplayName";
applicantList.ValueMember = "DisplayValue";
}