I need to create and send immediately campaigns in MailChimp.com. I used C# wrapper Percepective MCAPI.dll for this purpose.
from the MailChimp API, Its clear that we cannot lists but can create campaigns. I tried code but the campaignID is retured null; no exception thrown atleast. I did set the campaigntype to Auto.
here is my code snippet:
try
{
string apiKey = "api-us2"; // API KEY is valid
string emailAddress = "ravinderpal.singh#abc.net";
listsForEmailInput lstForEmailInput = new listsForEmailInput(apiKey, emailAddress);
listsForEmail cmd = new listsForEmail(lstForEmailInput);
listsForEmailOutput lstEmailOutPut = cmd.Execute();
List lstResults = lstEmailOutPut.result;
string listID = lstResults[0]; // Got Precraeted List ID( Valid Confirmed )
Console.WriteLine("\n" + listID);
// compaign Create
campaignCreateOptions campaignCreateOpt = new campaignCreateOptions();
campaignCreateOpt.list_id = listID;
campaignCreateOpt.subject = " New Campaign from dev_Anil";
campaignCreateOpt.from_email = "anil.k#abc.net";
campaignCreateOpt.from_name = "anil";
Dictionary content = new Dictionary();
content.Add("html", "Helloaasdsa");
content.Add("text", "Hi all !! this is dev_anil");
content.Add("url", "");
content.Add("archive", "");
campaignSegmentOptions csOptions = new campaignSegmentOptions();
csOptions.match = "any"; // Could not set Condition -- need help for this
// Need to set a Dictionary typeOptions because null is not supported
Dictionary typeOptions = new Dictionary();
campaignCreateParms campaignCreateParms = new campaignCreateParms(apiKey, EnumValues.campaign_type.auto, campaignCreateOpt, content, csOptions, typeOptions);
campaignCreateInput campaignCreateInput = new campaignCreateInput(campaignCreateParms);
campaignCreate campaignCreate = new campaignCreate(campaignCreateInput);
campaignCreateOutput ccOutput = campaignCreate.Execute(campaignCreateInput);
string abc = ccOutput.result; // This comes out to null
}
catch(Exception ee)
{
Console.WriteLine("\n\n Exception :" + ee.Message); // no exception
}
can anybody show me the right direction and what is wrong with the code.
any help would be much appreciated.
thanks.
I solved this problem and here is code as solution. here listID is precreated List ID in your account in Mailchimp.
private void CreateCampaignAndSend(string apiKey, string listID)
{
Int32 TemplateID = 100;
string campaignID =string.Empty;
// compaign Create Options
campaignCreateOptions campaignCreateOpt = new campaignCreateOptions();
campaignCreateOpt.list_id = listID;
campaignCreateOpt.subject = "subject";
campaignCreateOpt.from_email = "abc#xyz.com";
campaignCreateOpt.from_name = "abc";
campaignCreateOpt.template_id = TemplateID;
// Content
Dictionary<string, string> content = new Dictionary<string, string>();
content.Add("html_ArticleTitle1", "ArticleTitle1");
content.Add("html_ArticleTitle2","ArticleTitle2");
content.Add("html_ArticleTitle3", "ArticleTitle3");
content.Add("html_Article1", "Article1");
content.Add("html_Article2", "Article2");
// Conditions
List<campaignSegmentCondition> csCondition = new List<campaignSegmentCondition>();
campaignSegmentCondition csC = new campaignSegmentCondition();
csC.field = "interests-" + 123; // where 123 is the Grouping Id from listInterestGroupings()
csC.op = "all";
csC.value = "";
csCondition.Add(csC);
// Options
campaignSegmentOptions csOptions = new campaignSegmentOptions();
csOptions.match = "all";
// Type Options
Dictionary<string, string> typeOptions = new Dictionary<string, string>();
typeOptions.Add("offset-units", "days");
typeOptions.Add("offset-time", "0");
typeOptions.Add("offset-dir", "after");
// Create Campaigns
campaignCreate campaignCreate = new campaignCreate(new campaignCreateInput(apiKey, EnumValues.campaign_type.plaintext, campaignCreateOpt, content, csOptions, typeOptions));
campaignCreateOutput ccOutput = campaignCreate.Execute();
List<Api_Error> error = ccOutput.api_ErrorMessages; // Catching API Errors
if (error.Count <= 0)
{
campaignID = ccOutput.result;
}
else
{
foreach (Api_Error ae in error)
{
Console.WriteLine("\n ERROR Creating Campaign : ERRORCODE\t:" + ae.code + "\t ERROR\t:" + ae.error);
}
}
}
I removed the url and archive from the content. Then the campaign was created just fine:
// campaign Create
campaignCreateOptions campaignCreateOpt = new campaignCreateOptions();
campaignCreateOpt.list_id = listId;
campaignCreateOpt.subject = " New Campaign from Someemone";
campaignCreateOpt.from_email = "someone#home.com";
campaignCreateOpt.from_name = "someone";
Dictionary<string, string> content = new Dictionary<string, string>();
content.Add("html", "Lots of cool stuff here.");
campaignSegmentOptions csOptions = new campaignSegmentOptions();
csOptions.match = "any"; // Could not set Condition -- need help for this
// Need to set a Dictionary typeOptions because null is not supported
Dictionary<string,string> typeOptions = new Dictionary<string, string>();
campaignCreateParms campaignCreateParms = new campaignCreateParms(apiKey, EnumValues.campaign_type.trans, campaignCreateOpt, content, csOptions, typeOptions);
campaignCreateInput campaignCreateInput = new campaignCreateInput(campaignCreateParms);
campaignCreate campaignCreate = new campaignCreate(campaignCreateInput);
campaignCreateOutput ccOutput = campaignCreate.Execute(campaignCreateInput);
string newCampaignId = ccOutput.result; // Not null anymore
Related
I use
https://developers.facebook.com/tools/access_token/
I create an App. I want get Posts of the wall of me and my friends.
I try me/feed and me/posts but I get nothing.
I have this unit test.
Any suggestions?
[TestMethod]
public void Basic_using_SDK()
{
// http://blog.prabir.me/posts/facebook-csharp-sdk-making-requests
var fb = new Facebook.FacebookClient();
var result = (IDictionary<string, object>)fb.Get("4");
var id = (string)result["id"];
var name = (string)result["name"];
var firstName = (string)result["first_name"];
var lastName = (string)result["last_name"];
var link = (string)result["link"];
var username = (string)result["username"];
var gender = (string)result["gender"];
var male = (string)result["locale"];
var parameters = new Dictionary<string, object>();
parameters["fields"] = "id,name";
result = (IDictionary<string, object>)fb.Get("4", parameters);
id = (string)result["id"];
name = (string)result["name"];
dynamic result2 = fb.Get("4");
id = result2.id;
name = result2.name;
firstName = result2.first_name;
lastName = result2.last_name;
link = result2.link;
username = result2.username;
gender = result2.gender;
male = result2.locale;
dynamic parameters2 = new ExpandoObject();
parameters2.fields = "id,name";
dynamic result3 = fb.Get("4", parameters);
id = result3.id;
name = result3.name;
dynamic me = fb.Get("zuck");
firstName = me.first_name;
lastName = me.last_name;
var client = new FacebookClient(AccessToken);
dynamic me2 = client.Get("me");
string aboutMe = me2.about;
dynamic result4 = client.Get("/me/feed");
foreach (dynamic post in result4.data)
{
var fromName = post.from.name;
Console.WriteLine(fromName);
}
dynamic result5 = client.Get("/me/posts");
for (int i = 0; i < result5.Count; i++)
{
}
// https://www.facebook.com/profile.php?id=xxxxxxx
// https://graph.facebook.com/xxxxxxx
var uidKiquenet = "xxxxx";
var query = string.Format(#"SELECT status_id,message,time,source,uid,place_id
FROM status WHERE uid IN (SELECT uid FROM status WHERE uid = '" + uidKiquenet + "') ORDER BY time DESC");
dynamic parameters6 = new ExpandoObject();
parameters6.q = query;
dynamic results6 = fb.Get("/xxxxx?fields=id,name,age_range,about,email,first_name,gender");
string myMessage = "Hello from Test";
fb.PostTaskAsync("me/feed", new { message = myMessage }).ContinueWith(t =>
{
if (!t.IsFaulted)
{
string message = "Great, your message has been posted to you wall!";
Console.WriteLine(message);
}
});
fb.GetTaskAsync("me").ContinueWith(t =>
{
if (!t.IsFaulted)
{
var result11 = (IDictionary<string, object>)t.Result;
string myDetails = string.Format("Your name is: {0} {1} and your Facebook profile Url is: {3}",
(string)result11["first_name"], (string)result11["last_name"],
(string)result11["link"]);
Console.WriteLine(myDetails);
}
});
// This uses Facebook Query Language
// See https://developers.facebook.com/docs/technical-guides/fql/ for more information.
query = string.Format("SELECT uid,name,pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1={0}) ORDER BY name ASC", "me()");
fb.GetTaskAsync("fql", new { q = query }).ContinueWith(t =>
{
if (!t.IsFaulted)
{
var result1 = (IDictionary<string, object>)t.Result;
var data = (IList<object>)result1["data"];
var count = data.Count;
var message = string.Format("You have {0} friends", count);
Console.WriteLine(message);
foreach (IDictionary<string, object> friend in data)
Console.WriteLine((string)friend["name"]);
}
});
}
You must authorize with the correct permission in order to get access to feed posts. Try authorizing with user_posts, as it is explained in the docs: https://developers.facebook.com/docs/graph-api/reference/v2.3/user/feed#read
Be aware that this does not get you access to posts of friends, unless they posted on the wall of the authorized user.
About review, you may want to read this: https://developers.facebook.com/docs/facebook-login/review/faqs#what_is_review
Btw, FQL is deprecated and will only work in v2.0 Apps - not in newer ones.
Same thing happened to me . Here is my Solution
I made my project registered on Facebook developer console. Then I did my code same as you but could not get posts / information . After some time i submitted my application for app review to facebook team (it was still in early development phase) and after their feedback I got my code working . So pending Application review can be your issue also . This option is available in application setting . Give it a shot
Update
Another code sample is here
if (Request["code"] == null)
{
Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
FB_app_id, Request.Url.AbsoluteUri, FB_scope));
return false;
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}&perms=status_update"
, FB_app_id, Request.Url.AbsoluteUri, FB_scope, Request["code"].ToString(), FB_secret_id);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader rd = new StreamReader(response.GetResponseStream());
string vals = rd.ReadToEnd();
foreach (string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf('=')), token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf('=') - 1));
}
string access_token = tokens["access_token"];
Session["fb_access_token"] = access_token;
return true;
}
}
i am new to travelport universal api. i receive response from api. I perform LOW FARE SEARCH and in response the fare information and the flight information return in two different list.the problem is that i don't find any relationship in these LIST's. and also WHAT IS THE BEST WAY TO DECODE THE WSDL RESPONSE. i am using WSDL below is my code
string TargetBranch = "P7004961";
string OriginApplication = "uAPI";
string Origin="DXB";
string Destination="LHR";
string Departuredate = "2014-03-25T00:00:00";
string FlightStatus = "One-way";
string url = "https://americas-uapi.copy-webservices.travelport.com/B2BGateway/connect/uAPI/AirService";
string ReturnDate = "2014-04-05T00:00:00";
string UserName = "Universal API/uAPI6035036525-8ff7f8fc", Password = "DSXSEDn3fme9d6m2DfKP5rEaW";
LowFareSearchReq req = new LowFareSearchReq();
req.TargetBranch = TargetBranch;
BillingPointOfSaleInfo biPOS = new BillingPointOfSaleInfo();
biPOS.OriginApplication = OriginApplication;
req.BillingPointOfSaleInfo = biPOS;
/////////// Origin to Destination////////////////
SearchAirLeg airLeg = new SearchAirLeg();
Airport fromAirPort = new Airport() { Code = Origin };
typeSearchLocation fromTypLoc = new typeSearchLocation() { Item = fromAirPort };
airLeg.SearchOrigin = new typeSearchLocation[1] { fromTypLoc };
Airport toAirPort = new Airport() { Code = Destination };
typeSearchLocation toTypLoc = new typeSearchLocation() { Item = toAirPort };
airLeg.SearchDestination = new typeSearchLocation[1] { toTypLoc };
typeTimeSpec origDep = new typeTimeSpec() { PreferredTime = Departuredate };
airLeg.Items = new typeTimeSpec[1] { origDep };
/////////////////// Destination to Origin ////////////////////
SearchAirLeg returnLeg = new SearchAirLeg();
Airport RetfromAirport = new Airport() { Code = Destination };
typeSearchLocation fromLocation = new typeSearchLocation() { Item = RetfromAirport };
returnLeg.SearchOrigin = new typeSearchLocation[1] { fromLocation };
Airport retToAirpot = new Airport() { Code = Origin };
typeSearchLocation tolocation = new typeSearchLocation() { Item = retToAirpot };
returnLeg.SearchDestination = new typeSearchLocation[1] { tolocation };
typeTimeSpec retdate = new typeTimeSpec() { PreferredTime = ReturnDate };
returnLeg.Items = new typeTimeSpec[1] { retdate };
///////// checking for one way or return//////////////////////////
if (FlightStatus == "One-way")
{
req.Items = new object[] { airLeg };
}
else
{
req.Items = new object[] { airLeg, returnLeg };
}
AirSearchModifiers AirsearchModifier = new AirSearchModifiers()
{
DistanceType = typeDistance.KM,
IncludeFlightDetails = true,
PreferNonStop = true,
MaxSolutions = "300",
PreferredProviders= new Provider[1]{ new Provider(){ Code="1G"}}
};
req.AirSearchModifiers = AirsearchModifier;
SearchPassenger pass1 = new SearchPassenger() { Code = "ADT" };
req.SearchPassenger = new SearchPassenger[] { pass1 };
string Currency = "PKR";
AirPricingModifiers AirPriceMode = new AirPricingModifiers() { CurrencyType = Currency, };
req.AirPricingModifiers = AirPriceMode;
LowFareSearchRsp response = new LowFareSearchRsp();
AirLowFareSearchBinding binding = new AirLowFareSearchBinding();
binding.Url = url;
binding.Credentials = new NetworkCredential(UserName, Password);
response = binding.service(req);
Thanks to all.Finally i found result which is below quit easy in fact In the LowFareSearch response you get back among other info a list of AirSegments and a list of AirPricingSolutions. Each AirPricingSolution contains AirPricingInfo with the applicable SegmentRef keys and BookingCode info. Each SegmentRef key corresponds to a flight in the AirSegment list. This is how you know which flights (AirSegments) correspond to a specific price (AirPricingSolution).
I need to insert a new invoice for a particular customer , I can able to insert , but i don't have any idea about how to insert multiple items in invoice. How to use the property Items and ItemsElementName to insert multiple items.
If my question is unclear please let me know. I have attached the snapshot and code for reference.
Code:
protected void btnsendInvoiceDetails_Click(object sender, EventArgs e)
{
string accessToken = "lvprdRM1HLr6o11Bnip2fGizlXWbFfADnS1Btvm2L4VPOTRI";
string appToken = "297db54bb5526b494adb86fb2a41063192cd";
string accessTokenSecret = "JfSTrprW83JTXrSVHD3uf7th23gP0SOzBQcn4Nrt";
string consumerKey = "qyprdKLN5YHpCPSlWQZTiKVc28dywR";
string consumerSecret = "JPMNB37YnCPGU9m9vuXkF2M71lbDb7blhcLB7HeF";
string companyID = "813162085";
OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
ServiceContext context = new ServiceContext(oauthValidator,appToken,companyID, IntuitServicesType.QBO);
DataServices service = new DataServices(context);
InvoiceHeader a = new InvoiceHeader();
a.CustomerName = "Antivirus Norton Security";
a.CustomerId = new IdType { idDomain = idDomainEnum.QBO, Value = "6" };
a.TotalAmt = 157.00m;
a.SubTotalAmt = 37.00m;
a.ShipMethodName = "Gmail";
a.ShipMethodId = new IdType { idDomain = idDomainEnum.QBO, Value = "41" };
a.DocNumber = "1040";
a.DueDateSpecified = true;
// a.Item = 10.00m;
//a.ItemElementName = ItemChoiceType2.DiscountAmt;
DateTime dt = Convert.ToDateTime("08/07/2013");
a.DueDate = dt;
InvoiceLine mnm = new InvoiceLine();
mnm.Desc = "Antivirus Norton Security The Best Security ";
mnm.Id = new IdType { idDomain = idDomainEnum.QBO, Value = "25" };
mnm.Amount = 65.00m;
mnm.AmountSpecified = true;
// mnm.Items = "Europe";
//mnm.ItemsElementName = "Zebronic";
InvoiceLine[] invline = new InvoiceLine[] { mnm };
var invoices = new Intuit.Ipp.Data.Qbo.Invoice();
invoices.Header = a;
invoices.Line = invline;
var addedInvoice = service.Add(invoices);
var qboInvoices = service.FindAll(invoices, 1,10);
foreach (var qboinv in qboInvoices)
{
string id = Convert.ToString(qboinv.Id.Value);
}
GridView1.DataSource = invoices;
GridView1.DataBind();
}
Image:
Try this:
InvoiceLine i = new InvoiceLine();
i.ItemsElementName = new ItemsChoiceType2[1];
i.ItemsElementName[0] = ItemsChoiceType2.ItemId;
i.Items = new Intuit.Ipp.Data.Qbd.IdType[1];
i.Items[0] = new Intuit.Ipp.Data.Qbd.IdType() { idDomain = Intuit.Ipp.Data.Qbd.idDomainEnum.QBO, Value = "6" };
To get my data(users and books) from Firebird base I am using the following methods:
public static Dictionary<string, Users> getUsersFromDB()
{
Dictionary<string, Users> users_list = new Dictionary<string, Users>();
string reqestCommand = "SELECT id, user_type, user_nick, user_pass, user_fname, user_lname, user_identify, e_mail,address, registered FROM USERS";
string connectionString = connectionPath();
using (FbConnection fbDB = new FbConnection(connectionString))
{
fbDB.Open();
FbCommand reqest = new FbCommand(reqestCommand, fbDB);
using (FbDataReader reader = reqest.ExecuteReader())
{
while (reader.Read())
{
string key;
Users user = new Users();
user.ID = reader.GetInt32(0);
user.type = reader.GetString(1).Trim();
key = reader.GetString(2).Trim();
user.nick = key;
user.password = reader.GetString(3).Trim();
user.fName = reader.GetString(4).Trim();
user.lName = reader.GetString(5).Trim();
user.identify = reader.GetString(6).Trim();
user.email = reader.GetString(7).Trim();
user.address = reader.GetString(8).Trim();
user.registerDate = reader.GetString(9).Trim();
user.localOrInDb = "inDatabase";
users_list.Add(key, user);
}
}
fbDB.Close();
}
return users_list;
}
public static Dictionary<Guid, Books> getBooksFromDB()
{
Dictionary<Guid, Books> books_list = new Dictionary<Guid, Books>();
string reqestCommand = "SELECT book_id, book_title, book_author, book_genre, book_language, book_rel_date, book_page_number, book_available_amount, book_type FROM BOOKS";
string connectionString = connectionPath();
using (FbConnection fbDB = new FbConnection(connectionString))
{
fbDB.Open();
FbCommand reqest = new FbCommand(reqestCommand, fbDB);
using (FbDataReader reader = reqest.ExecuteReader())
{
while (reader.Read())
{
Guid key;
Books book = new Books();
Guid theGuid = new Guid(reader.GetString(0).Trim());
key = book.ID = theGuid;
book.title = reader.GetString(1).Trim();
book.author = reader.GetString(2).Trim();
book.genre = reader.GetString(3).Trim();
book.language = reader.GetString(4).Trim();
book.rel_date = reader.GetString(5).Trim();
book.page_number = reader.GetInt32(6);
book.amount = reader.GetInt32(7);
book.type = reader.GetString(8).Trim();
book.localOrInDb = "inDatabase";
books_list.Add(key, book);
}
}
fbDB.Close();
}
return books_list;
}
How can we see, they are almost same, so question:
Is it possible to make from them one function? Or would it be better to leave them separate?
You can pass a parameter that makes an instance of your target class from Reader:
public static Dictionary<K,T> GetFromDb<K,T>(Func<Reader,KeyValuePair<K,T> maker) {
var res = new Dictionary<K,T>();
// ... your code ...
while (reader.Read()) {
res.Add(maker(reader));
}
return res;
}
Now you can call your GetFromDb like this:
var users = GetFromDb<string,User>(reader => {
string key;
Users user = new Users();
user.ID = reader.GetInt32(0);
user.type = reader.GetString(1).Trim();
key = reader.GetString(2).Trim();
user.nick = key;
user.password = reader.GetString(3).Trim();
user.fName = reader.GetString(4).Trim();
user.lName = reader.GetString(5).Trim();
user.identify = reader.GetString(6).Trim();
user.email = reader.GetString(7).Trim();
user.address = reader.GetString(8).Trim();
user.registerDate = reader.GetString(9).Trim();
user.localOrInDb = "inDatabase";
return new KeyValuePair<string,User>(key, user);
});
Check this post
https://stackoverflow.com/a/1464929/988830
You can abstract the reader using extension method.
However you have to create the FBconnection everytime. If you try to put it in a function and access it from another one then you will get exception that reader is closed.
using uses IDisposible http://msdn.microsoft.com/en-us/library/system.idisposable.aspx
which closes the connection.
Another option
Start using orm like Entity framework or NHibernate which will map the table with your object.
Currently I’m having some difficulties with using new Magento's soap v2 from c# interface.
With php i was able to do something like this:
$params["created_at"]["from"] = date("Y-m-d H:i:s",Functions::convert_time($dataDa));
$params["created_at"]["to"] = date("Y-m-d H:i:s",Functions::convert_time($dataA));
MageInterface::getSingleton()->shipmentList($params);
In this mode i was able to find list of orders which were created from $dataDa to $dataA without problems. With c# however it seems that only the last one of the selectors work.
My code:
var cpf = new complexFilter[2];
cpf[0] = new complexFilter
{
key = "created_at",
value = new associativeEntity
{
key = "to",
value = uxDataA.DateTime.ToString("yy-MM-dd HH:mm:ss")
}
});
cpf[1] = new complexFilter
{
key = "created_at",
value = new associativeEntity
{
key = "from",
value = uxDataDa.DateTime.ToString("yy-MM-dd HH:mm:ss")
}
});
var filters = new filters();
filters.complex_filter = cpf;
var risultato = mage.salesOrderList(sessionKey, filters);
In this mode only created_at->from criteria is taken in consideration (it's like second complex filter override previous one with the same key). Ideas?
Thanks in advance.
This works for me :
private filters addFilter(filters filtresIn, string key, string op, string value)
{
filters filtres = filtresIn;
if (filtres == null)
filtres = new filters();
complexFilter compfiltres = new complexFilter();
compfiltres.key = key;
associativeEntity ass = new associativeEntity();
ass.key = op;
ass.value = value;
compfiltres.value = ass;
List<complexFilter> tmpLst;
if (filtres.complex_filter!=null)
tmpLst = filtres.complex_filter.ToList();
else tmpLst = new List<complexFilter>();
tmpLst.Add(compfiltres);
filtres.complex_filter = tmpLst.ToArray();
return filtres;
}
and call
{
Mage_Api_Model_Server_V2_HandlerPortTypeClient clientSoap = new Mage_Api_Model_Server_V2_HandlerPortTypeClient();
string sessionId = clientSoap.login(LOG, PASS);
filters filtres = new filters();
filtres = addFilter(filtres, "status", "eq", "processing");
filtres = addFilter(filtres, "created_at", "from", "2014-09-07 08:00:00");
filtres = addFilter(filtres, "created_at", "to", "2014-09-07 00:00:00");
salesOrderEntity[] lst = clientSoap.salesOrderList(sessionId, filtres);
}
Solved, there was a bug (or the feature?) in mage\sales\order\api\v2.php
See more info in this thread: http://www.magentocommerce.com/boards/viewthread/70368/