I am working on an MVC5 project, the client is interested in using MailChimp for sending emails. I have explored the MailChimp and wrappers ( MailChimp.NET ) and tried in my project as well. I tested the REST API as well and it seems to work , for example; I was able to grab lists and templates using REST API. But, still I am having issues with sending email through MailChimp.
So far, I have tried the following code and its working. Now I want to send an email to a newly registered user. Kindly give me detailed code example that How can I achieve this, because I am totally struck here..
var apiKey = "myapikey-us11";
var listId = "mylistid";
var subscribeRequest = new
{
apikey = apiKey,
id = listId,
email = new
{
email = "muhammad.waqas#seventechnology.co.uk"
},
double_optin = true,
};
var requestJson = JsonConvert.SerializeObject(subscribeRequest);
var reqresult = CallMailChimpApi("lists/", requestJson);
CallMailChimApi
private static string CallMailChimpApi(string method, string requestJson)
{
var endpoint = String.Format("https://{0}.api.mailchimp.com/3.0/{1}", "us11", method);
var wc = new WebClient();
try
{
return wc.UploadString(endpoint, requestJson);
}
catch (WebException we)
{
using (var sr = new StreamReader(we.Response.GetResponseStream()))
{
return sr.ReadToEnd();
}
}
}
I Use this function and it work successfully
public void SendEmailByApiMailChimp ()
{
try
{
string UserEmail = " Exemple#gmail.com ";
MailChimpManager mc = new MailChimpManager("16d***********-us14");
EmailParameter email = new EmailParameter()
{
Email = UserEmail
};
EmailParameter resulte = mc.Subscribe("yourlistnumber", email);
var test = resulte;
}
catch (Exception ex)
{
var ters = ex;
}
}
Related
I am using two .NET Core Web APIs; one for publishing content and another for subscribing that content using a NATS streaming server.
At publisher side
string clientID = "abc-publisher";
string clusterID = "test-cluster";
string subject = "testing Subject1";
string data = "Testing with the API";
byte[] payload = Encoding.UTF8.GetBytes(data);
try
{
var opts = StanOptions.GetDefaultOptions();
//opts.StartWithLastReceived();
opts.NatsURL = StanConsts.DefaultNatsURL;
using (var c = new StanConnectionFactory().CreateConnection(clusterID, clientID,opts))
{
string returnData = c.Publish(subject, payload, (obj, pubArgs) =>
{
string s = pubArgs.GUID;
});
}
}
catch (Exception ex)
{
string msg = ex.Message.ToString();
}
At Subscriber side
using (var c = new StanConnectionFactory().CreateConnection(clusterID, clientID)) {
var opts = StanSubscriptionOptions.GetDefaultOptions();
opts.StartWithLastReceived();
var s = c.Subscribe(subject, (obj, args) =>
{
str = Encoding.UTF8.GetString(args.Message.Data);
});
}
But when I run the projects I am unable to go to the callback method of the subscriber.
Sorry for the delay.
Check your server log, you should have gotten an error since your subject has spaces. In NATS, subjects cannot have spaces, more information here.
Hy... I'm learning twilio rightnow, and I have seen a post here http://www.markhagan.me/Samples/Send-SMS-Using-Twilio-ASPNet
I have made my own code because in above site "sendSMSMessage" is deprecated now, but Here is my code :
using System.Text;
using System.Threading.Tasks;
using Twilio;
namespace SMSUsingTwilio
{
class Program
{
static void Main(string[] args)
{
String ACCOUNT_SID = "ACMYSID";
String AUTH_TOKEN = "40MYAUTHTOKEN";
TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
Message Response = client.SendMessage("(732)305-8856", "+6285220446195", "Hellow Hyosoka Poipo :D");
Console.WriteLine(Response.Status);
Console.WriteLine(Response.AccountSid);
Console.WriteLine("SMS Berhasil di kirim");
Console.ReadLine();
}
}
}
The problem is I don't any sms message to my phone number and even I don't get any response in my C# project:
So what's wrong here...?? Please help..Thank you so much...:)
After seeing mr.David answer, I realized that my phone number was not yet verified. So go to this link for verifying my number:
https://www.twilio.com/user/account/phone-numbers/verified
After that, I run my project agian and here is the result :
Yeeeiii...Thanks so much for your comments and answer... I really appreciate it... :)
The above looks fine:
var message = client.SendMessage("(732)305-8856", "+6285220446195", "Hellow Hyosoka Poipo :D");
Example:
static void Main(string[] args)
{
string AccountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
string AuthToken = "[AuthToken]";
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var message = twilio.SendMessage("(732)305-8856", "+6285220446195", "Hellow Hyosoka Poipo :D");
);
Console.WriteLine(message.Sid);
}
Check this out:
https://www.twilio.com/docs/api/rest/sending-messages
I don't recognise your phone numbers, if the above example does not work it will be an issue with your account or the number format.
First of all, you need to install a Twillio NuGet package from Numget Manager
Otherwise,
You can write code Install-Package Twilio
in Package manager console.
You need to create Twillo account from https://www.twilio.com
Now you get AccountId, AuthToken etc
Then you will need to implement the following code in your project:
public async Task<string> SendTwilioSMS(string phoneNumber, string SMS)
{
string returnMessage = string.Empty;
string bodySMS = SMS;
var twilioAccountSid = "AC754fec249d22766caf0ae4e58a158271";
var twilioAuthToken = "cfecd5ff4d751677fc2e2875e3739b55";
var twilioMessagingServiceSid = "MGd57fcc863cb37dcff135aca43b4bb7d1";
var twilioPhoneNumber = "+919714285344";
bodySMS = SMS;
TwilioClient.Init(twilioAccountSid, twilioAuthToken);
try
{
MessageResource twillioResult = await MessageResource.CreateAsync(
to: new PhoneNumber(phoneNumber),
from: new PhoneNumber(twilioPhoneNumber),
body: bodySMS,
messagingServiceSid: twilioMessagingServiceSid
);
returnMessage = "Message sent";
}
catch (Exception err)
{
returnMessage = err.Message;
}
return returnMessage;
}
The value should be brought from appsettings file if using .Net Core.
public async Task SendSMS()
{
var sid = "0845-373A-90fy-5790";
var authToken = "5a983-498f94-2849o8934-28455s9";
try
{
TwilioClient.Init(sid , authToken );
var message = await MessageResource.CreateAsync(
body: "Hi",
from: new Twilio.Types.PhoneNumber("+12564598"),
to: new Twilio.Types.PhoneNumber("9467345243"));
}
catch (Exception ex)
{
//Log Exception
}
}
I am writing C# client for Instagram. I've registered my application and filled the fields: Application Name, Description, Website, OAuth redirect_uri. But I receive this error message in my C# client:
This client is not xAuth enabled.
I think the problem is in Website, OAuth redirect_uri fields. What values must I put in these fields?
Here is method that have to get access_token (HttpRequest class from xNet library):
private string GetAccessToken()
{
using (var request = new HttpRequest())
{
var urlParams = new RequestParams();
urlParams["client_id"] = "ce3c76b914cb4417b3721406d7fe3456";
urlParams["client_secret"] = "b8ad0c21ce8142d0a8c0fa2d2bd78f53";
urlParams["username"] = this.login;
urlParams["password"] = this.password;
urlParams["grant_type"] = "password";
urlParams["scope"] = "comments likes relationships";
try
{
this.json = request.Post("https://api.instagram.com/oauth/access_token", urlParams).ToString();
var values = JsonConvert.DeserializeObject<InstagramResponse>(this.json);
return values.access_token;
}
catch (Exception)
{
return null;
}
}
}
Working Platform: ASP.NET 4.0 C# ( Framework Agnostic )
Google GData is my dependency
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Documents;
I have two pages Auth and List.
Auth redirects to Google Server like this
public ActionResult Auth()
{
var target = Request.Url.ToString().ToLowerInvariant().Replace("auth", "list");
var scope = "https://docs.google.com/feeds/";
bool secure = false, session = true;
var authSubUrl = AuthSubUtil.getRequestUrl(target, scope, secure, session);
return new RedirectResult(authSubUrl);
}
Now it reaches the List Page if Authentication is successful.
public ActionResult List()
{
if (Request.QueryString["token"] != null)
{
String singleUseToken = Request.QueryString["token"];
string consumerKey = "www.blahblah.net";
string consumerSecret = "my_key";
string sessionToken = AuthSubUtil.exchangeForSessionToken(singleUseToken, null).ToString();
var authFactory = new GOAuthRequestFactory("writely", "qwd-asd-01");
authFactory.Token = sessionToken;
authFactory.ConsumerKey = consumerKey;
authFactory.ConsumerSecret = consumerSecret;
//authFactory.TokenSecret = "";
try
{
var service = new DocumentsService(authFactory.ApplicationName) { RequestFactory = authFactory };
var query = new DocumentsListQuery();
query.Title = "project";
var feed = service.Query(query);
var result = feed.Entries.ToList().ConvertAll(a => a.Title.Text);
return View(result);
}
catch (GDataRequestException gdre)
{
throw;
}
}
}
This fails at the line var feed = service.Query(query); with the error
Execution of request failed: https://docs.google.com/feeds/default/private/full?title=project
The HttpStatusCode recieved on the catch block is HttpStatusCode.Unauthorized
What is wrong with this code? Do I need to get TokenSecret? If so how?
You need to request a token from Google and use it to intialize your DocumentsService instance.
Here's an example using Google's ContactsService. It should be the same for the DocumentsService.
Service service = new ContactsService("My Contacts Application");
service.setUserCredentials("your_email_address_here#gmail.com", "yourpassword");
var token = service.QueryClientLoginToken();
service.SetAuthenticationToken(token);
But as you mentioned, you are using AuthSub. I jumped the gun a bit too fast.
I see that you are requesting a session token. According to the documentation of the API you must use the session token to authenticate requests to the service by placing the token in the Authorization header. After you've set the session token, you can use the Google Data APIs client library.
Here's a complete example (by Google) on how to use AuthSub with the .NET client library:
http://code.google.com/intl/nl-NL/apis/gdata/articles/authsub_dotnet.html
Let me include a shortened example:
GAuthSubRequestFactory authFactory =
new GAuthSubRequestFactory("cl", "TesterApp");
authFactory.Token = (String) Session["token"];
CalendarService service = new CalendarService(authFactory.ApplicationName);
service.RequestFactory = authFactory;
EventQuery query = new EventQuery();
query.Uri = new Uri("http://www.google.com/calendar/feeds/default/private/full");
EventFeed calFeed = service.Query(query);
foreach (Google.GData.Calendar.EventEntry entry in calFeed.Entries)
{
//...
}
And if I see correctly your example code pretty follows the same steps, except that you set the ConsumerKey and ConsumerSecret for the AuthFactory which is not done in the example by Google.
Used the 3-legged OAuth in the Google Data Protocol Client Libraries
Sample Code
string CONSUMER_KEY = "www.bherila.net";
string CONSUMER_SECRET = "RpKF7ykWt8C6At74TR4_wyIb";
string APPLICATION_NAME = "bwh-wssearch-01";
string SCOPE = "https://docs.google.com/feeds/";
public ActionResult Auth()
{
string callbackURL = String.Format("{0}{1}", Request.Url.ToString(), "List");
OAuthParameters parameters = new OAuthParameters()
{
ConsumerKey = CONSUMER_KEY,
ConsumerSecret = CONSUMER_SECRET,
Scope = SCOPE,
Callback = callbackURL,
SignatureMethod = "HMAC-SHA1"
};
OAuthUtil.GetUnauthorizedRequestToken(parameters);
string authorizationUrl = OAuthUtil.CreateUserAuthorizationUrl(parameters);
Session["parameters"] = parameters;
ViewBag.AuthUrl = authorizationUrl;
return View();
}
public ActionResult List()
{
if (Session["parameters"] != null)
{
OAuthParameters parameters = Session["parameters"] as OAuthParameters;
OAuthUtil.UpdateOAuthParametersFromCallback(Request.Url.Query, parameters);
try
{
OAuthUtil.GetAccessToken(parameters);
GOAuthRequestFactory authFactory = new GOAuthRequestFactory("writely", APPLICATION_NAME, parameters);
var service = new DocumentsService(authFactory.ApplicationName);
service.RequestFactory = authFactory;
var query = new DocumentsListQuery();
//query.Title = "recipe";
var feed = service.Query(query);
var docs = new List<string>();
foreach (DocumentEntry entry in feed.Entries)
{
docs.Add(entry.Title.Text);
}
//var result = feed.Entries.ToList().ConvertAll(a => a.Title.Text);
return View(docs);
}
catch (GDataRequestException gdre)
{
HttpWebResponse response = (HttpWebResponse)gdre.Response;
//bad auth token, clear session and refresh the page
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
Session.Clear();
Response.Write(gdre.Message);
}
else
{
Response.Write("Error processing request: " + gdre.ToString());
}
throw;
}
}
else
{
return RedirectToAction("Index");
}
}
This 2-legged sample never worked for me for google docs.
I need to create a user control in either vb.net or c# to search a RightNow CRM database. I have the documentation on their XML API, but I'm not sure how to post to their parser and then catch the return data and display it on the page.
Any sample code would be greatly appreciated!
Link to API: http://community.rightnow.com/customer/documentation/integration/82_crm_integration.pdf
I don't know RightNow CRM, but according to the documentation you can send the XML requests using HTTP post. The simplest way to do this in .NET is using the WebClient class. Alternatively you might want to take a look at the HttpWebRequest/HttpWebResponse classes. Here is some sample code using WebClient:
using System.Net;
using System.Text;
using System;
namespace RightNowSample
{
class Program
{
static void Main(string[] args)
{
string serviceUrl = "http://<your_domain>/cgi-bin/<your_interface>.cfg/php/xml_api/parse.php";
WebClient webClient = new WebClient();
string requestXml =
#"<connector>
<function name=""ans_get"">
<parameter name=""args"" type=""pair"">
<pair name=""id"" type=""integer"">33</pair>
<pair name=""sub_tbl"" type='pair'>
<pair name=""tbl_id"" type=""integer"">164</pair>
</pair>
</parameter>
</function>
</connector>";
string secString = "";
string postData = string.Format("xml_doc={0}, sec_string={1}", requestXml, secString);
byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
byte[] responseDataBytes = webClient.UploadData(serviceUrl, "POST", postDataBytes);
string responseData = Encoding.UTF8.GetString(responseDataBytes);
Console.WriteLine(responseData);
}
}
}
I have no access to RightNow CRM, so I could not test this, but it can serve as s tarting point for you.
This will Create a Contact in Right now
class Program
{
private RightNowSyncPortClient _Service;
public Program()
{
_Service = new RightNowSyncPortClient();
_Service.ClientCredentials.UserName.UserName = "Rightnow UID";
_Service.ClientCredentials.UserName.Password = "Right now password";
}
private Contact Contactinfo()
{
Contact newContact = new Contact();
PersonName personName = new PersonName();
personName.First = "conatctname";
personName.Last = "conatctlastname";
newContact.Name = personName;
Email[] emailArray = new Email[1];
emailArray[0] = new Email();
emailArray[0].action = ActionEnum.add;
emailArray[0].actionSpecified = true;
emailArray[0].Address = "mail#mail.com";
NamedID addressType = new NamedID();
ID addressTypeID = new ID();
addressTypeID.id = 1;
addressType.ID = addressTypeID;
addressType.ID.idSpecified = true;
emailArray[0].AddressType = addressType;
emailArray[0].Invalid = false;
emailArray[0].InvalidSpecified = true;
newContact.Emails = emailArray;
return newContact;
}
public long CreateContact()
{
Contact newContact = Contactinfo();
//Set the application ID in the client info header
ClientInfoHeader clientInfoHeader = new ClientInfoHeader();
clientInfoHeader.AppID = ".NET Getting Started";
//Set the create processing options, allow external events and rules to execute
CreateProcessingOptions createProcessingOptions = new CreateProcessingOptions();
createProcessingOptions.SuppressExternalEvents = false;
createProcessingOptions.SuppressRules = false;
RNObject[] createObjects = new RNObject[] { newContact };
//Invoke the create operation on the RightNow server
RNObject[] createResults = _Service.Create(clientInfoHeader, createObjects, createProcessingOptions);
//We only created a single contact, this will be at index 0 of the results
newContact = createResults[0] as Contact;
return newContact.ID.id;
}
static void Main(string[] args)
{
Program RBSP = new Program();
try
{
long newContactID = RBSP.CreateContact();
System.Console.WriteLine("New Contact Created with ID: " + newContactID);
}
catch (FaultException ex)
{
Console.WriteLine(ex.Code);
Console.WriteLine(ex.Message);
}
System.Console.Read();
}
}