How to refund amount of paypal adaptive payment using PayPal.AdaptivePayments SDK? - c#

I`m using PayPal.AdaptivePayments sdk for chained payment and refund process of chained payment.
Using following methods:
for payment : pay() method
for refund : refund() method as per sdk.
When try to refund with payKey then getting response with status: "NO_API_ACCESS_TO_RECEIVER"
Currently I`m sandbox account on development.
I have also followed paypal developer api/sdk docs but still getting same problem.
So please help me to refund process with status of "Refunded".
I have already review post related to this on stack-overflow but I didn`t proper solution in any post.
https://devtools-paypal.com/guide/ap_chained_payment?interactive=ON&env=sandbox
private void Refund(HttpContext contextHttp)
{
NameValueCollection parameters = contextHttp.Request.Params;
RefundRequest request = new RefundRequest(new RequestEnvelope("en_US"));
// Set optional parameters
if(parameters["receiverEmail"].Length > 0)
{
//(Required) Amount to be paid to the receiver
string[] amt = contextHttp.Request.Form.GetValues("receiverAmount");
// Maximum length: 127 characters
string[] receiverEmail = contextHttp.Request.Form.GetValues("receiverEmail");
//Telephone country code
string[] phoneCountry = contextHttp.Request.Form.GetValues("phoneCountry");
string[] phoneNumber = contextHttp.Request.Form.GetValues("phoneNumber");
//Telephone extension
string[] phoneExtn = contextHttp.Request.Form.GetValues("phoneExtn");
string[] primaryReceiver = contextHttp.Request.Form.GetValues("primaryReceiver");
string[] invoiceId = contextHttp.Request.Form.GetValues("invoiceId");
string[] paymentType = contextHttp.Request.Form.GetValues("paymentType");
//(Optional) The transaction subtype for the payment.
string[] paymentSubType = contextHttp.Request.Form.GetValues("paymentSubType");
List<Receiver> receivers = new List<Receiver>();
for(int i=0; i<amt.Length; i++) {
Receiver r = new Receiver(Convert.ToDecimal(amt[i]));
r.email = receiverEmail[i];
r.primary = Convert.ToBoolean(primaryReceiver[i]);
if(invoiceId[i] != string.Empty) {
r.invoiceId = invoiceId[i];
}
if(paymentType[i] != string.Empty) {
r.paymentType = paymentType[i];
}
if(paymentSubType[i] != string.Empty) {
r.paymentSubType = paymentSubType[i];
}
if(phoneCountry[i] != string.Empty && phoneNumber[i] != string.Empty) {
r.phone = new PhoneNumberType(phoneCountry[i], phoneNumber[i]);
if(phoneExtn[i] != string.Empty) {
r.phone.extension = phoneExtn[i];
}
}
receivers.Add(r);
}
request.receiverList = new ReceiverList(receivers);
}
if(parameters["currencyCode"] != string.Empty) {
request.currencyCode = parameters["currencyCode"];
}
if(parameters["payKey"] != string.Empty) {
request.payKey = parameters["payKey"];
}
if(parameters["transactionId"] != string.Empty) {
request.transactionId = parameters["transactionId"];
}
if(parameters["trackingId"] != string.Empty) {
request.trackingId = parameters["trackingId"];
}
AdaptivePaymentsService service = null;
RefundResponse response = null;
try
{
Dictionary<string, string> configurationMap = Configuration.GetAcctAndConfig();
service = new AdaptivePaymentsService(configurationMap);
response = service.Refund(request);
}
catch (System.Exception e)
{
contextHttp.Response.Write(e.Message);
return;
}
Dictionary<string, string> responseValues = new Dictionary<string, string>();
// string redirectUrl = null;
string redirectUrl = null;
if (!(response.responseEnvelope.ack == AckCode.FAILURE) &&
!(response.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
{
responseValues.Add("Currency code", response.currencyCode);
int idx = 1;
foreach (RefundInfo refund in response.refundInfoList.refundInfo)
{
//Receiver's email address.Maximum length: 127 characters
responseValues.Add("Refund receiver " + idx, refund.receiver.email);
// Amount to be refunded to the receiver.
responseValues.Add("Refund amount " + idx, refund.receiver.amount.ToString());
responseValues.Add("Refund status " + idx, refund.refundStatus);
responseValues.Add("Acknowledgement", response.responseEnvelope.ack.ToString());
}
}
Display(contextHttp, "Refund", responseValues, service.getLastRequest(), service.getLastResponse(), response.error, redirectUrl);
}

Related

Sendgrid dynamic data not being sent to Template

This is how I send my email:
public async System.Threading.Tasks.Task<string> SendInternalEmail(BasicEmailStructureViewModel Structure, List<string> AdditionalVariables, TenantEmailTemplate tenantEmailTemplate, TenantCommunication tenantCommunication, string ReceiverId, string ReceiverEmail, string ReceiverName, string CampaignName)
{
try
{
var client = new SendGridClient(tenantCommunication.SendgridApiKey);
var message = new SendGridMessage();
message.SetFrom(new EmailAddress(tenantCommunication.SendgridPrimarySender, tenantCommunication.SendgridPrimarySenderTag));
message.AddTo(new EmailAddress(ReceiverEmail, $"{ReceiverName}"));
message.Subject = tenantEmailTemplate.Subject;
message.SetTemplateId(tenantEmailTemplate.TemplateId);
List<string> jsonVars = new List<string>();
var subjectString = #$"""subject"":""{tenantEmailTemplate.Subject}""";
jsonVars.Add(subjectString);
foreach (PropertyInfo prop in Structure.GetType().GetProperties())
{
var variableString = #$"""{prop.Name}"":""{prop.GetValue(Structure, null)}""";
}
for (var i = 0; i < AdditionalVariables.Count; i++)
{
jsonVars.Add(AdditionalVariables[i]);
}
var flattenList = "{" + string.Join(",", jsonVars) + "}";
var emailData = Newtonsoft.Json.JsonConvert.DeserializeObject<object>(flattenList);
message.SetTemplateData(emailData);
if (CampaignName != null && CampaignName != "")
{
message.AddCustomArg("CampaignName", CampaignName);
}
var response = await client.SendEmailAsync(message);
if (response.IsSuccessStatusCode == true)
{
return Guid.NewGuid().ToString();
}
else
{
var errorMessage = response.Body.ReadAsStringAsync().Result;
return errorMessage;
}
}
catch(Exception e)
{
if (e != null)
{
return e.Message;
}
}
return "Invalid Email";
}
A typical input to this function will be like this:
var variableString =
#$"""verification_link"":""www.website.com?Key={Input.Key}""";
My email sends normally, however, none of the variables that I have set have been sent through. This is based roughly off the template sample on github: https://github.com/sendgrid/sendgrid-csharp/blob/main/examples/templates/templates.cs
Is there another sample I can use or what is the correct way to send variables dynamically?
I don't think that is the best way to construct the JSON for your dynamic template variables.
Would it be possible for you to build the variables as an object and then serialize them. Like:
var templateData = new {
subject = tenantEmailTemplate.Subjectm
otherVariableName = otherVariable
};
string emailData = JsonConvert.SerializeObject(templateData);
message.SetTemplateData(emailData);

C# Roslyn CompletionService where to get method overload information

I've got a method that returning back from CompletionService.GetDescriptionAsync(Document, CompletionItem) gives me the following description:
void SQL.GetSQLiteDB(string url) (+ 1 overload)
This is a method I made on a Xamarin project, here are both method signatures:
public static void GetSQLiteDB(string url);
public static string GetSQLiteDB(string url, string name);
What's the Roslyn way to get information on both?
Here's how I'm setting up completions:
async Task InitCodeCompletion()
{
host = MefHostServices.Create(MefHostServices.DefaultAssemblies);
workspace = new AdhocWorkspace(host);
Type[] types =
{
typeof(object),
typeof(System.Linq.Enumerable),
typeof(System.Collections.IEnumerable),
typeof(Console),
typeof(System.Reflection.Assembly),
typeof(List<>),
typeof(Type),
typeof(SQL)
};
imports = types.Select(x => x.Namespace).Distinct().ToImmutableArray();
assemblies = types.Select(x => x.Assembly).Distinct().ToImmutableArray();
references = assemblies.Select(t => MetadataReference.CreateFromFile(t.Location) as MetadataReference).ToImmutableArray();
compilationOptions = new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
usings: imports);
projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "Script", "Script", LanguageNames.CSharp, isSubmission: true)
.WithMetadataReferences(references).WithCompilationOptions(compilationOptions);
project = workspace.AddProject(projectInfo);
documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "Script", sourceCodeKind: SourceCodeKind.Script,
loader: TextLoader.From(TextAndVersion.Create(SourceText.From(""), VersionStamp.Create())));
document = workspace.AddDocument(documentInfo);
var services = workspace.Services;
completionService = CompletionService.GetService(document);
}
async Task<CodeCompletionResults> GetCompletions(string code)
{
string codeModified = "using SQL = XamTestNET5.Services.SQLiteGeneratorService; " + Environment.NewLine;
codeModified += "using HtmlSvc = XamTestNET5.Services.HtmlRetrievalService;" + Environment.NewLine;
// ^^^ The above two lines set up some simple namespace aliases in my project, if you know how to put this in a separate project document and use it in code completion please let me know in comments as otherwise doing so gives me an exception that you can't have multiple syntax trees
codeModified += code;
var source = SourceText.From(codeModified);
document = document.WithText(source);
// cursor position is at the end
var position = source.Length;
var completions = await completionService.GetCompletionsAsync(document, position);
return new CodeCompletionResults() { InputCode = code, ModifiedCode = codeModified, Completions = completions };
}
Here's how I'm getting them now and putting them in a browser control:
private async void CSharpShellEnvironment_EntryCodeCompletionEntry(object sender, CSharpShellEnvironment.EntryEventArgs e)
{
if (e.Value != "")
{
CodeCompletionResults results = await GetCompletions(e.Value);
CompletionList list = results.Completions;
if (list != null)
{
if (list.Items != null)
{
StringBuilder sb = new StringBuilder();
foreach (var item in list.Items)
{
string spanText = (item.Span.Start != item.Span.End) ? results.ModifiedCode.Substring(item.Span.Start, item.Span.Length) : "";
bool recommended = spanText == "" ? true : item.DisplayText.StartsWith(spanText);
if (recommended)
{
string fText = item.DisplayText.Substring(spanText.Length);
string props = "";
foreach(var p in item.Properties)
{
props += $"<span data-key=\"{p.Key}\" data-value=\"{p.Value}\"></span>";
}
string tags = "";
foreach(var t in item.Tags)
{
tags += $"<span data-tag=\"{t}\"></span>";
}
string descStr = "";
if (item.Tags != null)
{
if (item.Tags.Where(x => x.ToLower() == "method").FirstOrDefault() != null && item.Tags.Where(x => x.ToLower() == "public").FirstOrDefault() != null)
{
var desc = await completionService.GetDescriptionAsync(document, item);
descStr += $"<span data-desc=\"{desc.Text}\">";
foreach(var part in desc.TaggedParts)
{
descStr += $"<span data-desc-part-tag=\"{part.Tag}\" data-desc-part-text=\"{part.Text}\"></span>";
}
descStr += "</span>";
}
}
sb.AppendLine($"<div class=\"codecompleteentry\" data-display-text=\"{item.DisplayText}\" data-span-text=\"{spanText}\" data-final-text=\"{fText}\">{props}{tags}{descStr}{fText}</div>");
}
}
string scriptInputClick = "Array.prototype.forEach.call(document.getElementsByClassName('codecompleteentry'), function(el) { el.addEventListener('click', function(elem) { var text = { MessageType: 'CodeCompletion', Parameters: JSON.stringify({ DataDisplayText: el.getAttribute('data-display-text'), DataSpanText: el.getAttribute('data-span-text'), DataFinalText: el.getAttribute('data-final-text') }), Message: el.innerText }; window.chrome.webview.postMessage(text); } ); });";
sb.AppendLine($"<script type=\"text/javascript\">{scriptInputClick}</script>");
env.EnterCodeCompletionResponse(sb.ToString());
}
else
{
env.EnterCodeCompletionResponse(strNoSuggestions);
}
}
else
{
env.EnterCodeCompletionResponse(strNoSuggestions);
}
}
else
{
env.EnterCodeCompletionResponse(strNoSuggestions);
}
}
It seems on the surface that CompletionSurface has everything you need, but it doesn't, you need to reference the Document's SemanticModel in order to get all of the signature overloads of a method when the user types ( on a method during code completion.
It wasn't very obvious to me until I started looking through the RoslynPad source, which I recommend doing for a practical example: https://github.com/aelij/RoslynPad
List<IEnumerable<ReferencedSymbol>> allMethodRefs = new List<IEnumerable<ReferencedSymbol>>();
async Task<CodeCompletionResults> GetCompletions(string code)
{
string codeModified = "using SQL = XamTestNET5.Services.SQLiteGeneratorService; " + Environment.NewLine;
codeModified += "using HtmlSvc = XamTestNET5.Services.HtmlRetrievalService;" + Environment.NewLine;
// ^^^ I put my namespace aliases in the same SyntaxTree for now,
// I'd like a better solution though.
codeModified += code;
var source = SourceText.From(codeModified);
document = document.WithText(source);
// cursor position is at the end
var position = source.Length;
var completions = await completionService.GetCompletionsAsync(document, position);
syntaxRoot = await document.GetSyntaxRootAsync();
semanticModel = await document.GetSemanticModelAsync();
var methods = syntaxRoot.DescendantNodes().OfType<InvocationExpressionSyntax>();
allMethodRefs = new List<IEnumerable<ReferencedSymbol>>();
if (methods != null)
{
if (methods.Count() > 0)
{
foreach(var m in methods)
{
var info = semanticModel.GetSymbolInfo(m);
if (info.Symbol != null)
{
allMethodRefs.Add(await SymbolFinder.FindReferencesAsync(info.Symbol, solution));
}
else
{
foreach(var symbol in info.CandidateSymbols)
{
allMethodRefs.Add(await SymbolFinder.FindReferencesAsync(symbol, solution));
}
}
}
}
}
return new CodeCompletionResults() { InputCode = code, ModifiedCode = codeModified, Completions = completions };
}

Your Campaign is not ready to send in mailchimp api v3 using C#

I created code to send campaign immediately by consuming mailchimp api v3.0 using C# console. When i tried in free account everything goes well, but when i upgrade my account in premium i got this problem (only add 2 members).
My scenario:
create audience => success
add member subscriber into audience that i created => success
create campaign with specific template => success
send cehcklist in campaign already created => return is_ready false
send campaign => return Your Campaign is not ready to send
When I try to run my console program using console c# consume mailchimp api I got this error:
Type: http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/
Title: Bad Request
Status: 400
Detail: Your Campaign is not ready to send.
instance: 214b85f4-a288-44e7-b890-35925d8601ac
When I checked campaign into mailchimp website portal, I saw a message like this:
To send, you need at least 1 subscriber in your list.
This means that there is no recipients in my campaign, here is detail screenshot:
Please has anyone ever faced this, too? I really appreciate any suggestions.
Is there any way to resolve that issue before sending campaign? Because when I checked mailchimp portal (based on screenshot shown above), I back into campaign list then open my campaign above the problem automatically resolve, this is my confusing one.
Because mailchimp api v3.0 has limitation only 500 members subscriber on one call, finally I created class to partition my list:
//partition list of members more than 500
public static class Extensions
{
public static List<List<T>> SplitPartition<T>(this IEnumerable<T> collection, int size)
{
var chunks = new List<List<T>>();
var count = 0;
var temp = new List<T>();
foreach (var element in collection)
{
if (count++ == size)
{
chunks.Add(temp);
temp = new List<T>();
count = 1;
}
temp.Add(element);
}
chunks.Add(temp);
return chunks;
}
}
this my main code using several scenario to handle single method can call in many way:
public class MailChimpProcessor
{
static MailChimpProcessor()
{
//initialize
ApiHelper.InitializeClient(baseUrl, apiKey);
}
public class MailChimpResponse
{
public string result { get; set; }
public GlobalErrorResponseModel error { get; set; }
}
public static MailChimpResponse MailChimpSendCampaign(SendEmailCampaignModel model)
{
MailChimpResponse mailchimpResult = new MailChimpResponse();
#region PROPERTY OBJECT AUDIENCE
Contact contact = new Contact()
{
company = model.audience_company,
address1 = model.audience_address1,
address2 = model.address2Config,
city = model.audience_city,
state = model.audience_state,
zip = model.audience_zip,
country = model.audience_country,
phone = model.phoneConfig
};
CampaignDefaults campaign = new CampaignDefaults()
{
from_name = model.campaign_from_name,
from_email = model.campaign_reply_to,
subject = model.campaign_subject,
language = "en"
};
AudienceRequestModel audienceModel = new AudienceRequestModel();
audienceModel.name = model.audience_name;
audienceModel.contact = contact;
audienceModel.permission_reminder = permissionReminderConfig;
audienceModel.use_archive_bar = true;
audienceModel.campaign_defaults = campaign;
audienceModel.notify_on_subscribe = "";
audienceModel.notify_on_unsubscribe = "";
audienceModel.email_type_option = true;
#endregion
#region PROPERTY OBJECT MEMBER
List<Member> members = new List<Member>();
//prevent duplicate email_address
var queryMemberList = model.members.GroupBy(x => x.email_address).Select(x => x.First());
foreach (var item in queryMemberList)
{
members.Add(new Member
{
email_address = item.email_address.ToLower(),
status = "subscribed",
status_if_new = "subscribed",
merge_fields = new MergeFields()
{
FNAME = item.merge_fields.FNAME,
LNAME = item.merge_fields.LNAME
}
});
}
bool isUploadContact = false;
int offset = 0;
const int numberPerBatch = 500; // maximum member per execution.
double LoopMax = Math.Ceiling(members.Count / (double)numberPerBatch);
//partition array
var PartitionMembers = members.SplitPartition(numberPerBatch);
#endregion
//create audience using post method
var audienceResult = AudienceProcessor.PostAudienceAsync(audienceModel).Result;
#region PROPERTY OBJECT CAMPAIGN
Recipients recipient = new Recipients()
{
list_id = audienceResult.ResponseModel != null ? audienceResult.ResponseModel.id : "0"
};
Settings setting = new Settings()
{
subject_line = model.campaign_subject,
title = model.campaign_title,
reply_to = model.campaign_reply_to,
from_name = model.campaign_from_name,
template_id = model.campaign_template_id
};
CampaignRequestModel campaignModel = new CampaignRequestModel();
campaignModel.recipients = recipient;
campaignModel.type = "regular";
campaignModel.settings = setting;
#endregion
if (audienceResult.ResponseModel != null)
{
MemberProcessor.MemberResponse memberResult = new MemberProcessor.MemberResponse();
while (offset < LoopMax)
{
MemberRequestModel memberModel = new MemberRequestModel();
memberModel.members = PartitionMembers[offset];//list based on index of array
memberModel.update_existing = true;
//post contact member
memberResult = MemberProcessor.PostContatcAsync(memberModel, audienceResult.ResponseModel.id).Result;
if (memberResult.ResponseModel != null)
{
isUploadContact = true;
}
else
{
isUploadContact = false;
}
offset++; // increment
}
//create campaign
if (isUploadContact)//belum tereksekusi
{
//sleep thread 20 seconds after upload subcriber members
System.Threading.Thread.Sleep(20000);
//create campaign using post method
var campaignResult = CampaignProcessor.PostCampaignAsync(campaignModel).Result;
if (campaignResult.ResponseModel.id != null)
{
#region USING ITERATION TO CHECK CAMPAIGN
CampaignProcessor.CampaignResponseCheckList campaignChecklist = new CampaignProcessor.CampaignResponseCheckList();
bool isReadySend = false;
int check = 0;
while (check <= 10) //maksimum 10 iteration
{
//check campaign using get method
campaignChecklist = CampaignProcessor.GetCheckListCampaign(campaignResult.ResponseModel.id).Result;
if (campaignChecklist.ResponseModel.is_ready == true) //when error model is not null
{
isReadySend = true;
break;
}
else
{
isReadySend = false;
}
System.Threading.Thread.Sleep(1000); // will puase every 1 second
check++;
}
if (isReadySend)
{
//sleep action before send campaign
System.Threading.Thread.Sleep(2000);
//send campaign
var sendCampaignResult = CampaignProcessor.SendCampaignAsync(campaignResult.ResponseModel.id).Result;
if (sendCampaignResult.ErrorModel == null)
mailchimpResult.result = sendCampaignResult.ResponseModel;
else
mailchimpResult.error = sendCampaignResult.ErrorModel; //i got this return indicate that my campaign is not ready
}
else
{
mailchimpResult.error = campaignChecklist.ErrorModel;
mailchimpResult.result = $"failed Check List Campaign / Your Campaign is not ready to send.";
}
#endregion
}
else
{
mailchimpResult.error = campaignResult.ErrorModel;
mailchimpResult.result = "failed create Campaign";
}
}
else
{
mailchimpResult.result = $"failed create contact: {offset}";
mailchimpResult.error = memberResult.ErrorModel;
}
}
else
{
mailchimpResult.error = audienceResult.ErrorModel;
mailchimpResult.result = "failed create Audience";
}
return mailchimpResult;
}
}
Try this code below
System.Threading.Thread.Sleep(40000); //try change this one
//create campaign using post method
var campaignResult = CampaignProcessor.PostCampaignAsync(campaignModel).Result;
if (campaignResult.ResponseModel.id != null)
{
#region USING ITERATION TO CHECK CAMPAIGN
CampaignProcessor.CampaignResponseCheckList campaignChecklist = new CampaignProcessor.CampaignResponseCheckList();
bool isReadySend = false;
int check = 0;
while (true) //just change this condition
{
//check campaign using get method
campaignChecklist = CampaignProcessor.GetCheckListCampaign(campaignResult.ResponseModel.id).Result;
if (campaignChecklist.ResponseModel.is_ready == true) //when error model is not null
{
isReadySend = true;
break;
}
else
{
isReadySend = false;
}
check++;
}
if (isReadySend)
{
//send campaign
var sendCampaignResult = CampaignProcessor.SendCampaignAsync(campaignResult.ResponseModel.id).Result;
if (sendCampaignResult.ErrorModel == null)
mailchimpResult.result = sendCampaignResult.ResponseModel;
else
mailchimpResult.error = sendCampaignResult.ErrorModel; //i got this return indicate that my campaign is not ready
}
else
{
mailchimpResult.error = campaignChecklist.ErrorModel;
mailchimpResult.result = $"failed Check List Campaign / Your Campaign is not ready to send.";
}
#endregion

The given key was not present in the dictionary when trying posting to facebook

I need help from anyone that has ever done and solved the problem when trying to use this API, and got an error of "The Given Key Was Not Present..."
I got an error when trying post to facebook timeline., the accesstoken, and facebookid are already store in the database.
and here is the code :
public void SendComment(string p_strIdFB, string p_strMessage, string p_strWebLink, string p_strLinkAlias,
string p_strCaption, string p_strDescription, string p_strPictLink, string p_strIconLink, string p_strIdgods)
{
//FacebookSettings set = new FacebookSettings();
//set.AppId = v_strApiKey;
//set.AppSecret = v_strApiSecret;
try
{
IDictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("message", p_strMessage);
if (ConverterManager.ConvertEmptyTextIntoString(p_strWebLink, "") != "")
{
dict.Add("link", p_strWebLink);
if (ConverterManager.ConvertEmptyTextIntoString(p_strPictLink, "") != "")
{
dict.Add("picture", p_strPictLink);
}
if (ConverterManager.ConvertEmptyTextIntoString(p_strLinkAlias, "") != "")
{
dict.Add("name", p_strLinkAlias);
}
if (ConverterManager.ConvertEmptyTextIntoString(p_strCaption, "") != "")
{
dict.Add("caption", p_strCaption);
}
if (ConverterManager.ConvertEmptyTextIntoString(p_strDescription, "") != "")
{
dict.Add("description", p_strDescription);
}
}
if (ConverterManager.ConvertEmptyTextIntoString(p_strIconLink, "") != "")
{
dict.Add("icon", p_strIconLink);
}
//FacebookApp app = new FacebookApp(set);
//app.Api("me/feed", dict, HttpMethod.Post);
string idgods = "";
idgods = p_strIdgods;
BLGodsProfile objBLGodsProfile = new BLGodsProfile();
tbmgodsprofile objGods = objBLGodsProfile.GetAccessToken(idgods);
//FacebookWebClient fwc = new FacebookWebClient();
var fwc = new FacebookClient(objGods.accesstoken);
FacebookWebClient ff = new FacebookWebClient(objGods.accesstoken);
ff.Post("/" + objGods.iduserfb + "/feed", dict);
}
catch(Exception ex)
{
Console.WriteLine("This User : {0} Got Error Posting Facebook : {1}",p_strIdgods, ex.Message);
}
}
and here is the code for posting it to the facebook
private static void PostShoutToFb1(string p_strMessage, string idgods)
{
BLFb objBLFb = new BLFb(System.Configuration.ConfigurationManager.AppSettings["FbApiKey"],
System.Configuration.ConfigurationManager.AppSettings["FbApiSecret"]);
TdoFacebookUser objFbUser = objBLFb.GetFacebookUser();
try
{
objBLFb.SendComment(objFbUser.Id, p_strMessage, "", "", "", "", "", "", idgods);
}
catch(Exception ex)
{
LogException(ex, "GodsFeed");
}
}
it's seem like the error is with the objBLFb.SendComment, cause when i'm trying to posting using mobile that i've developed, it's ok.
trims.

Could someone provide a C# example using itemsearch from Amazon Web Services

I am trying to use Amazon Web Services to query Artist and title information and receive album art back. Using C# I cannot find any examples that come even close to this. All of the examples online are outdated and do not work with AWS' newer version.
There is an open Source project on CodePlex you might want to take a look at.... It's A .NET Library for Amazon's Web Services. S3, SQS, FPS, EC2, and DevPay
It could be as simple as this(as shown on codeplex):
S3Client s3 = new S3Client("myAWSKey", "MyAWSPassword");
bool success = s3.Connect();
S3Client s3 = new S3Client("key", "secret"):
var buckets = from b in s3.Buckets
where b.Name == "demo"
select b;
foreach(Bucket b in buckets)
{
Console.WriteLine(b.About());
}
Here you go for what it's worth. This is code within an Asp.Net control to display book information. You can probably adapt it for your purposes easily enough. Or at least give you a starting-point. If you really want, I'd be happy to bundle the control up and send it your way.
if (!(string.IsNullOrEmpty(ISBN) && string.IsNullOrEmpty(ASIN)))
{
AWSECommerceService service = new AWSECommerceService();
ItemLookup lookup = new ItemLookup();
ItemLookupRequest request = new ItemLookupRequest();
lookup.AssociateTag = ConfigurationManager.AppSettings["AssociatesTag"];
lookup.AWSAccessKeyId = ConfigurationManager.AppSettings["AWSAccessKey"];
if (string.IsNullOrEmpty(ASIN))
{
request.IdType = ItemLookupRequestIdType.ISBN;
request.ItemId = new string[] { ISBN.Replace("-", "") };
}
else
{
request.IdType = ItemLookupRequestIdType.ASIN;
request.ItemId = new string[] { ASIN };
}
request.ResponseGroup = ConfigurationManager.AppSettings["AWSResponseGroups"].Split(new char[] { ' ', ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
lookup.Request = new ItemLookupRequest[] { request };
ItemLookupResponse response = service.ItemLookup(lookup);
if (response.Items.Length > 0 && response.Items[0].Item.Length > 0)
{
Item item = response.Items[0].Item[0];
if (item.MediumImage == null)
{
bookImageHyperlink.Visible = false;
}
else
{
bookImageHyperlink.ImageUrl = item.MediumImage.URL;
}
bookImageHyperlink.NavigateUrl = item.DetailPageURL;
bookTitleHyperlink.Text = item.ItemAttributes.Title;
bookTitleHyperlink.NavigateUrl = item.DetailPageURL;
if (item.OfferSummary.LowestNewPrice == null)
{
if (item.OfferSummary.LowestUsedPrice == null)
{
priceHyperlink.Visible = false;
}
else
{
priceHyperlink.Text = string.Format("Buy used {0}", item.OfferSummary.LowestUsedPrice.FormattedPrice);
priceHyperlink.NavigateUrl = item.DetailPageURL;
}
}
else
{
priceHyperlink.Text = string.Format("Buy new {0}", item.OfferSummary.LowestNewPrice.FormattedPrice);
priceHyperlink.NavigateUrl = item.DetailPageURL;
}
if (item.ItemAttributes.Author != null)
{
authorLabel.Text = string.Format("By {0}", string.Join(", ", item.ItemAttributes.Author));
}
else
{
authorLabel.Text = string.Format("By {0}", string.Join(", ", item.ItemAttributes.Creator.Select(c => c.Value).ToArray()));
}
ItemLink link = item.ItemLinks.Where(i => i.Description.Contains("Wishlist")).FirstOrDefault();
if (link == null)
{
wishListHyperlink.Visible = false;
}
else
{
wishListHyperlink.NavigateUrl = link.URL;
}
}
}

Categories