I'm working with a third-party who are posting information via HTTP POST to a .NET site I host locally. The POST is successful but I need to have the site send a success/failure response to the POST.
I have looked around but have been unable to find any suggestions to meet this need.
Please let me know if I can further clarify anything.
Thank you.
Edit: To include the code.
if (!string.IsNullOrEmpty(nvc["id"]) )
{
/* Populate the variables with the POST data
* Check first that the data is not empty or null */
if (!string.IsNullOrEmpty(nvc["id"]))
{ leadID = nvc["id"]; }
if (!string.IsNullOrEmpty(nvc["FN"]))
{ fn = nvc["FN"]; }
if (!string.IsNullOrEmpty(nvc["LN"]))
{ ln = nvc["LN"]; }
if (!string.IsNullOrEmpty(nvc["EMAIL"]))
{ email = nvc["EMAIL"]; }
if (!string.IsNullOrEmpty(nvc["PHONE"]))
{ phone = nvc["PHONE"]; }
if (!string.IsNullOrEmpty(nvc["ADDRESS"]))
{ address = nvc["ADDRESS"]; }
if (!string.IsNullOrEmpty(nvc["CITY"]))
{ city = nvc["CITY"]; }
if (!string.IsNullOrEmpty(nvc["STATE"]))
{ state = nvc["STATE"]; }
if (!string.IsNullOrEmpty(nvc["ZIP"]))
{ zip = nvc["ZIP"]; }
if (!string.IsNullOrEmpty(nvc["GENDER"]))
{ gender = nvc["GENDER"]; }
if (!string.IsNullOrEmpty(nvc["BIRTHDAY"]))
{ birthday = nvc["BIRTHDAY"]; }
if (!string.IsNullOrEmpty(nvc["TB"]))
{ tobacco = nvc["tobacco"]; }
// if (!string.IsNullOrEmpty(nvc["PPCSource"]))
// { PPCSource = nvc["PPCSource"]; }
if (!string.IsNullOrEmpty(nvc["GC_Source"]))
{ GC_Source__c = nvc["GC_Source"]; }
if (!string.IsNullOrEmpty(nvc["GC_Medium"]))
{ GC_Medium__c = nvc["GC_Medium"]; }
if (!string.IsNullOrEmpty(nvc["GC_Term"]))
{ GC_Term__c = nvc["GC_Term"]; }
if (!string.IsNullOrEmpty(nvc["GC_Content"]))
{ GC_Content__c = nvc["GC_Content"]; }
if (!string.IsNullOrEmpty(nvc["GC_Campaign"]))
{ GC_Campaign__c = nvc["GC_Campaign"]; }
if (!string.IsNullOrEmpty(nvc["GC_Custom_Segment"]))
{ GC_Custom_Segment__c = nvc["GC_Custom_Segment"]; }
if (!string.IsNullOrEmpty(nvc["GC_Num_of_Visits"]))
{ GC_Num_of_Visits__c = nvc["GC_Num_of_Visits"]; }
googleCookie = "Source: " + GC_Source__c + "; Medium: " + GC_Medium__c + "; Term: " + GC_Term__c + "; Content: " + GC_Content__c + "; Camp: " + GC_Campaign__c + "; Segment: " + GC_Custom_Segment__c + "; Visits: " + GC_Num_of_Visits__c;
GC_Source__c = "PPCSource";
if (ln != null & !string.IsNullOrEmpty(ln))
{
/* Call SetClientFunction with the POST Parameters Passed */
string result = SetClient(leadID, fn, ln, email, phone, address,city, state, zip, gender, birthday, tobacco, PPCSource, googleCookie, 0, GC_Source__c, GC_Medium__c, GC_Term__c);
SendNotice(GC_Source__c, fn, ln, result);
}
Related
I am creating a program that uses Firebase Google auth to SignIn/SignUp in c#. And Firestore as a database. I need to save the data of new users who signup. But I don't know how to differentiate new user who signs up and old user who sign in using google auth.
How to find this
Nothing i tried works.
private void OnSignIn()
{
GoogleSignIn.Configuration = configuration;
GoogleSignIn.Configuration.UseGameSignIn = false;
GoogleSignIn.Configuration.RequestIdToken = true;
AddToInformation("Calling SignIn");
GoogleSignIn.DefaultInstance.SignIn().ContinueWith(OnAuthenticationFinished);
}
internal void OnAuthenticationFinished(Task<GoogleSignInUser> task)
{
if (task.IsFaulted)
{
using (IEnumerator<Exception> enumerator = task.Exception.InnerExceptions.GetEnumerator())
{
if (enumerator.MoveNext())
{
GoogleSignIn.SignInException error = (GoogleSignIn.SignInException)enumerator.Current;
AddToInformation("Got Error: " + error.Status + " " + error.Message);
}
else
{
AddToInformation("Got Unexpected Exception?!?" + task.Exception);
}
}
}
else if (task.IsCanceled)
{
AddToInformation("Canceled");
}
else
{
AddToInformation("Welcome: " + task.Result.DisplayName + "!");
// AddToInformation("User Status: "+ task.Result.)
AddToInformation("Email = " + task.Result.Email);
AddToInformation("Google ID Token = " + task.Result.IdToken);
AddToInformation("Email = " + task.Result.Email);
SignInWithGoogleOnFirebase(task.Result.IdToken);
}
}
private void SignInWithGoogleOnFirebase(string idToken)
{
Credential credential = GoogleAuthProvider.GetCredential(idToken, null);
auth.SignInWithCredentialAsync(credential).ContinueWith(task =>
{
AggregateException ex = task.Exception;
if (ex != null)
{
if (ex.InnerExceptions[0] is FirebaseException inner && (inner.ErrorCode != 0))
AddToInformation("\nError code = " + inner.ErrorCode + " Message = " + inner.Message);
}
else
{
AddToInformation("Sign In Successful.");
}
});
}
When SignInWithCredentialAsync completes, you get back a FirebaseUser object. This object has Metadata property with two values: CreationTimestamp and LastSignInTimestamp. If those values are the same or really close to each other, the user was just created.
I'm new to working with async and I'm trying to build a Cefsharp application that collects data from an external API, stores it in local variables and then exports these through JavaScript to HTML. It's not a beautiful implementation and I'm sure my code is pretty awful but here goes:
My application performs a tick every 5 seconds, where it executes a HTTP Post request and stores the result in a QuickType (app.quicktype.io) list. This is the tick:
private async void timer1_Tick(object sender, EventArgs e)
{
await chromeBrowser.WaitForInitialLoadAsync();
if (httpPost.ConnectionSuccesful())
{
var devtoolsContext = await chromeBrowser.CreateDevToolsContextAsync();
var postResult = await httpPost.SendPost("robot_info");
try {
var result = Welcome.FromJson(postResult);
foreach (var robot in result.Result.Robots.Select((value, i) => (value, i)))
{
Console.WriteLine(robot.value.Id);
if (robot.value.ChargingStateCode == 9 || robot.value.ChargingStateCode == 12)
await devtoolsContext.EvaluateFunctionAsync("function setBatteryCharge() { var batteryLevel = jQuery('#robot" + robot.i + "Charge'); batteryLevel.css('width', "+ robot.value.StateOfCharge + " + '%'); batteryLevel.text('Charging'); batteryLevel.addClass('high'); batteryLevel.removeClass('medium'); batteryLevel.removeClass('low'); }");
else if (robot.value.StateOfCharge > 75)
await devtoolsContext.EvaluateFunctionAsync("function setBatteryHigh() { var batteryLevel = jQuery('#robot" + robot.i + "Charge'); batteryLevel.css('width', " + robot.value.StateOfCharge + " + '%'); batteryLevel.text(" + robot.value.StateOfCharge + " + '%'); batteryLevel.addClass('high'); batteryLevel.removeClass('medium'); batteryLevel.removeClass('low'); }");
else if (robot.value.StateOfCharge >= 50)
await devtoolsContext.EvaluateFunctionAsync("function setBatteryMedium() { var batteryLevel = jQuery('#robot" + robot.i + "Charge'); batteryLevel.css('width', " + robot.value.StateOfCharge + " + '%'); batteryLevel.text(" + robot.value.StateOfCharge + " + '%'); batteryLevel.addClass('medium'); batteryLevel.removeClass('high'); batteryLevel.removeClass('low'); }");
else
await devtoolsContext.EvaluateFunctionAsync("function setBatteryLow() { var batteryLevel = jQuery('#robot" + robot.i + "Charge'); batteryLevel.css('width', " + robot.value.StateOfCharge + " + '%'); batteryLevel.text(" + robot.value.StateOfCharge + " + '%'); batteryLevel.addClass('low'); batteryLevel.removeClass('high'); batteryLevel.removeClass('medium'); }");
}
}
catch (ArgumentNullException Nex) {
Console.Write("[Error] - " + Nex.Message);
}
catch (Exception ex)
{
Console.WriteLine("[Error] - " + ex.Message);
}
}
else
Console.WriteLine("[Error] - Check connection or access to API server.");
}
I'm currently trying to update the battery level and it successfully does this for the first tick (the JavaScript works as intended and both the css, classes and text is changed). Then it stops working. I've checked that the correct results are coming in from the HTTP Post and that the data is stored properly in the local variables. The problem seems to occur in the foreach. I've tried to read up about async a bit but I can't seem to find the culprit. After the first execution of the code, something seems to be blocking the iteration of the for each. I'm using Cefsharp.Winforms and Cefsharp.Puppeteer.
Any idea on why this is happening? Also thankful for any pointers or tips on how to improve the code.
EDIT: This is the Console Output
[Query] Sending post request to xxx with method 'robot_info'
[Success] - API Post Request was succesful.
PR1#11
PR1#15
[Query] Sending post request to xxx with method 'robot_info'
[Success] - API Post Request was succesful.
PR1#11
[Query] Sending post request to xxx with method 'robot_info'
[Success] - API Post Request was succesful.
PR1#11
The first iteration goes through fine.
EDIT2: This is the timer
public void InitTimer()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 5000;
timer1.Start();
}
EDIT3: Method SendPost
public async Task<string> SendPost(string method)
{
HttpClient httpClient = new HttpClient();
string data = new JavaScriptSerializer().Serialize(new
{
jsonrpc = "2.0",
method = method,
id = Guid.NewGuid().ToString()
});
StringContent content = new StringContent(data, System.Text.Encoding.UTF8, "application/json");
try
{
Console.WriteLine("[Query] Sending post request to " + url.ToString() + " with method '" + method + "'");
HttpResponseMessage response = await httpClient.PostAsync(url, content).ConfigureAwait(false);
string result = await response.Content.ReadAsStringAsync();
if (IsValidJson(result))
{
Console.WriteLine("[Success] - API Post Request was succesful.");
return result;
}
else
return null;
} catch (HttpRequestException hre)
{
Console.WriteLine("[Error]: " + hre);
return null;
}
}
EDIT4: Structure of Welcome
public partial class Welcome
{
[JsonProperty("jsonrpc")]
public string Jsonrpc { get; set; }
[JsonProperty("result")]
public Result Result { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
}
public partial class Result
{
[JsonProperty("timestamp")]
public long Timestamp { get; set; }
[JsonProperty("robots")]
public List<Robot> Robots { get; set; }
}
Robots is a list with a bunch of longs and ints.
I have a Xamarin.Forms based application which uses operation with device contact like adding new contact and updating existing contact. Adding new contacts works, but update contact is not working. I used DependencyService of Xamarin.forms to update contacts on android. First i lookup for that contact and get its' Id if it exist.
Below is my code
void OnUpdate(){
var Id = LookupByPhone(phoneNumber, companyName+ " " + teamName);
if(Id!="0")
{
UpdateContact(phoneNumber, Id,companyName,teamName);
return;
}
}
string LookupByPhone(string phoneNumber, string query = "")
{
var Id = "0";
try
{
var context = MainActivity.Instance;
var uri = ContactsContract.Contacts.ContentUri;
uri = ContactsContract.CommonDataKinds.Phone.ContentUri;
string[] projection = {
ContactsContract.Contacts.InterfaceConsts.Id,
InterfaceConsts.DisplayName,
ContactsContract.CommonDataKinds.Phone.Number
};
var cursor = context.ContentResolver.Query(uri, projection, null, null, null);
if (cursor.MoveToFirst())
{
do
{
var id = cursor.GetString(cursor.GetColumnIndex(projection[0]));
var nm = cursor.GetString(cursor.GetColumnIndex(projection[1]));
var number = cursor.GetString(cursor.GetColumnIndex(projection[2]));
Id = id;
if (nm == query)
break;
//break;
} while (cursor.MoveToNext());
}
cursor.Close();
}
catch (Exception ex)
{
LogController.LogError(ex);
}
return Id;
}
void UpdateContact(string phonenumber, string id, string givenName, string familyName)
{
ContentProviderOperation.Builder builder = ContentProviderOperation.NewUpdate(ContactsContract.Data.ContentUri);
List<ContentProviderOperation> ops = new List<ContentProviderOperation>();
if (!string.IsNullOrWhiteSpace(givenName) && !string.IsNullOrWhiteSpace(familyName))
{
// Name
String nameSelection = ContactsContract.Data.InterfaceConsts.ContactId + " = ? AND "
+ ContactsContract.Data.InterfaceConsts.Mimetype + " = ? ";
String[] nameSelectionArgs = {
id.ToString(),
ContactsContract.CommonDataKinds.StructuredName.ContentItemType
};
builder.WithSelection(nameSelection, nameSelectionArgs);
builder.WithValue(ContactsContract.CommonDataKinds.StructuredName.GivenName, givenName);
builder.WithValue(ContactsContract.CommonDataKinds.StructuredName.FamilyName, familyName);
builder.WithValue(ContactsContract.CommonDataKinds.StructuredName.DisplayName, givenName + " " + familyName);
ops.Add(builder.Build());
}
#region Phone update
// CellPhone
String phoneSelection = ContactsContract.Data.InterfaceConsts.ContactId + " = ? AND " +
ContactsContract.Data.InterfaceConsts.Mimetype + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.InterfaceConsts.Type + " = ?";
String[] phoneselectionArgs = {
id.ToString(),
ContactsContract.CommonDataKinds.Phone.ContentItemType,
PhoneDataKind.Mobile.ToString()
};
builder = ContentProviderOperation.NewUpdate(ContactsContract.Data.ContentUri);
builder.WithSelection(phoneSelection, phoneselectionArgs);
builder.WithValue(ContactsContract.CommonDataKinds.Phone.Number, phonenumber);
builder.WithValue(ContactsContract.CommonDataKinds.Phone.InterfaceConsts.Type, PhoneDataKind.Mobile.ToString());
ops.Add(builder.Build());
#endregion
// Update the contact
ContentProviderResult[] result;
try
{
// the result return count{0}
var result = MainActivity.Instance.ContentResolver.ApplyBatch(ContactsContract.Authority, ops);
}
catch (Exception ex)
{
LogController.LogError("Error updating phone:" + phonenumber,ex);
}
}
There are no error or exception. Any thought on this.
The method which gets the id should be like this (I removed the first parameter since it's not used in your method):
string LookupByPhone(string name)
{
string id = "0";
var uri = ContactsContract.Contacts.ContentUri;
var cursor = this.ContentResolver.Query(
uri,
new String[] { ContactsContract.Contacts.InterfaceConsts.Id },
ContactsContract.Contacts.InterfaceConsts.DisplayName +
"='" + name + "'", null, null);
if (cursor.MoveToNext())
{
id = cursor.GetString(cursor.GetColumnIndex(ContactsContract.Contacts.InterfaceConsts.Id));
}
cursor.Close();
return id;
}
You can see I get the id by query the name that is what you are using companyName + " " + teamName
I want to get the "offer-listing" using amazon API.
I have explored by myself but there is not clue to get it.
it would be nice if someone suggest me the API end point to get the offer-listing or alternative
You can either scrap the offering page or use the Amazon's Product's API and call:
GetLowestOfferListingsForSKU to get offer listing including your self(you can use $request->setExcludeMe(TRUE) to exclude your self)
GetMyPriceForSKU to get just your offer listing
This API calls will return Landing price,Shipping price,Listing price where Landing price is your selling price + shipping price. None of above API call includes seller's name or any identity, so if you'r after seller's name and selling price you better of scrapping the offering page.
Here is the code I used:
$asin amazon product's ASIN
$sku is amazon product's SKU
$pos_data array contains all Amazon API's credentials
$fba_check is 'Y' or 'N' whether the ASIN is FBA(Fulfilled by Amazon) or not
function init_pro_api($asin, $sku, $pos_data, $fba_check)
{
$try = 0;
while($try < 2)
{
$offers_list = "";
$AWS_ACCESS_KEY_ID = $pos_data['azn_access_key'];
$AWS_SECRET_ACCESS_KEY = $pos_data['azn_secret_access_key'];
$APPLICATION_NAME = $pos_data['azn_app_name'];
$APPLICATION_VERSION = $pos_data['azn_app_version'];
$MERCHANT_ID = $pos_data['azn_merchant_id'];
$MARKETPLACE_ID = $pos_data['azn_marketplace_id'];
$platform = $pos_data['azn_platform_variant'];
if($platform == "uk")
{
$serviceURL = "https://mws.amazonservices.co.uk/Products/2011-10-01";
}
else
$serviceURL = "https://mws-eu.amazonservices.com/Products/2011-10-01";
$DATE_FORMAT = "Y-m-d";
$config = array(
'ServiceURL' => $serviceURL,
'ProxyHost' => null,
'ProxyPort' => -1,
'MaxErrorRetry' => 3,
);
$service = new MarketplaceWebServiceProducts_Client($AWS_ACCESS_KEY_ID, $AWS_SECRET_ACCESS_KEY, $APPLICATION_NAME, $APPLICATION_VERSION, $config);
// Get My Price
$request = new MarketplaceWebServiceProducts_Model_GetMyPriceForSKURequest();
$request->setSellerId($MERCHANT_ID);
$request->setMarketplaceId($MARKETPLACE_ID);
$sku_list = new MarketplaceWebServiceProducts_Model_SellerSKUListType();
$sku_list->setSellerSKU($sku);
$request->setSellerSKUList($sku_list);
$my_offer = invokeGetMyPriceForSKU($service, $request, $fba_check);
// Get Other Sellers Lowest Offering Price
$request = new MarketplaceWebServiceProducts_Model_GetLowestOfferListingsForSKURequest();
$request->setSellerId($MERCHANT_ID);
$request->setMarketplaceId($MARKETPLACE_ID);
$request->setItemCondition("New");
$request->setExcludeMe(TRUE);
$sku_list = new MarketplaceWebServiceProducts_Model_SellerSKUListType();
$sku_list->setSellerSKU($sku);
$request->setSellerSKUList($sku_list);
$other_low_offers = invokeGetLowestOfferListingsForSKU($service, $request);
if($my_offer != "" or $my_offer != NULL)
{
$offers_list["MyOffer"] = $my_offer;
}
if($other_low_offers != "" or $other_low_offers != NULL)
{
$offers_list["OtherOffer"] = $other_low_offers;
}
if(isset($offers_list["OtherOffer"][0]))
if($offers_list["OtherOffer"][0] != "")
break;
$try++;
}
return $offers_list;
}
function invokeGetMyPriceForSKU(MarketplaceWebServiceProducts_Interface $service, $request, $fba_check)
{
try
{
$my_response_data = "";
$pre_check_xml_data = array();
$xml_feed_counter = 0;
$response = $service->GetMyPriceForSKU($request);
$dom = new DOMDocument();
$dom->loadXML($response->toXML());
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$xml_data = $dom->saveXML();
$doc = new DOMDocument;
$doc->preserveWhiteSpace = FALSE;
$doc->loadXML($xml_data);
$offer_length = $doc->getElementsByTagName('Offer')->length;
$fba_index = "";
$normal_index = "";
for($o = 0; $o < $offer_length; $o++)
{
$pre_check_xml_data[$o]["LandedPrice"] = $doc->getElementsByTagName('LandedPrice')->item($o)->lastChild->nodeValue;
$pre_check_xml_data[$o]["ListingPrice"] = $doc->getElementsByTagName('ListingPrice')->item($o)->lastChild->nodeValue;
$pre_check_xml_data[$o]["Shipping"] = $doc->getElementsByTagName('Shipping')->item($o)->lastChild->nodeValue;
$pre_check_xml_data[$o]["FulfillmentChannel"] = $doc->getElementsByTagName('FulfillmentChannel')->item($o)->nodeValue;
if($fba_check == "Y")
{
if($doc->getElementsByTagName('FulfillmentChannel')->item($o)->nodeValue == "AMAZON")
{
$fba_index = $o;
break;
}
}
elseif($fba_check == "N")
{
if($doc->getElementsByTagName('FulfillmentChannel')->item($o)->nodeValue == "MERCHANT")
{
$normal_index = $o;
break;
}
}
}
if($fba_check == "Y")
{
if($fba_index === "")
{
$my_response_data[0]["LandedPrice"] = "";
$my_response_data[0]["ListingPrice"] = "";
$my_response_data[0]["Shipping"] = "";
$my_response_data[0]["Fulfillment"] = "";
return $my_response_data;
}
else
{
$my_response_data[0] = $pre_check_xml_data[$fba_index];
return $my_response_data;
}
}
else
{
$my_response_data[0] = $pre_check_xml_data[$normal_index];
return $my_response_data;
}
}
catch(MarketplaceWebServiceProducts_Exception $ex)
{
echo("Caught Exception: " . $ex->getMessage() . "\n");
echo("Response Status Code: " . $ex->getStatusCode() . "\n");
echo("Error Code: " . $ex->getErrorCode() . "\n");
echo("Error Type: " . $ex->getErrorType() . "\n");
echo("Request ID: " . $ex->getRequestId() . "\n");
echo("XML: " . $ex->getXML() . "\n");
echo("ResponseHeaderMetadata: " . $ex->getResponseHeaderMetadata() . "\n");
}
}
function invokeGetLowestOfferListingsForSKU(MarketplaceWebServiceProducts_Interface $service, $request)
{
try
{
$response_data = "";
$counter = 0;
$response = $service->getLowestOfferListingsForSKU($request);
$getLowestOfferListingsForSKUResultList = $response->getGetLowestOfferListingsForSKUResult();
foreach($getLowestOfferListingsForSKUResultList as $getLowestOfferListingsForSKUResult)
{
if($getLowestOfferListingsForSKUResult->isSetProduct())
{
$product = $getLowestOfferListingsForSKUResult->getProduct();
if($product->isSetLowestOfferListings())
{
$lowestOfferListings = $product->getLowestOfferListings();
$lowestOfferListingList = $lowestOfferListings->getLowestOfferListing();
foreach($lowestOfferListingList as $lowestOfferListing)
{
if($lowestOfferListing->isSetQualifiers())
{
$qualifiers = $lowestOfferListing->getQualifiers();
if($qualifiers->isSetFulfillmentChannel())
{
$response_data[$counter]["Fulfilled_By"] = $qualifiers->getFulfillmentChannel();
}
if($qualifiers->isSetShippingTime())
{
$shippingTime = $qualifiers->getShippingTime();
if($shippingTime->isSetMax())
{
$response_data[$counter]["ShippingTime"] = $shippingTime->getMax();
}
}
}
if($lowestOfferListing->isSetPrice())
{
$price1 = $lowestOfferListing->getPrice();
if($price1->isSetLandedPrice())
{
$landedPrice1 = $price1->getLandedPrice();
if($landedPrice1->isSetAmount())
{
$response_data[$counter]["LandedPrice"] = $landedPrice1->getAmount();
}
}
if($price1->isSetListingPrice())
{
$listingPrice1 = $price1->getListingPrice();
if($listingPrice1->isSetAmount())
{
$response_data[$counter]["ListingPrice"] = $listingPrice1->getAmount();
}
}
if($price1->isSetShipping())
{
$shipping1 = $price1->getShipping();
if($shipping1->isSetAmount())
{
$response_data[$counter]["Shipping"] = $shipping1->getAmount() . "\n";
}
}
}
$counter++;
}
}
}
if($getLowestOfferListingsForSKUResult->isSetError())
{
$error = $getLowestOfferListingsForSKUResult->getError();
if($error->isSetMessage())
{
$response_data = $error->getMessage() . "\n";
}
}
}
return $response_data;
}
catch(MarketplaceWebServiceProducts_Exception $ex)
{
echo("Caught Exception: " . $ex->getMessage() . "\n");
echo("Response Status Code: " . $ex->getStatusCode() . "\n");
echo("Error Code: " . $ex->getErrorCode() . "\n");
echo("Error Type: " . $ex->getErrorType() . "\n");
echo("Request ID: " . $ex->getRequestId() . "\n");
echo("XML: " . $ex->getXML() . "\n");
}
}
You can use the Amazon MWS products API like Keyur states. They provide PHP, C#, and Java example code and it's easy to work with.
If you want real-time price change notifications on products you are currently selling, subscribe to the AnyOfferChangedNotification notification. They have example code for that too. http://docs.developer.amazonservices.com/en_US/notifications/Notifications_AnyOfferChangedNotification.html
I'm doing some stuff with this right now and, if it helps anyone, I'm using the Advertising API and have found that if you make a request like this:
String requestString = "Service=AWSECommerceService"
+ "&Version=2009-03-31"
+ "&Operation=ItemLookup"
+ "&AssociateTag=some-associate-tag"
+ "&ItemId=" + your-item-id
+ "&ResponseGroup=BrowseNodes,OfferFull,ItemAttributes";
then you can look at the XPath //detailpageurl and you should get what you were expecting.
While sending email via System.Net.Mail to multiple recipients (one single email with multiple recipients), if one recipients address fail, will the rest reach the email?
There might be duplicates of the same question, but I'm asking something different in contrast.
For prompting such question, I was taken into consideration of Email clients available like Outlook where such does not happen even if one single address failed. Perhaps, System.Net.Mail is a lightweight client and does not allow such functionality? Or is it the way I'm writing my code incorrectly.
I was asked as if why this happens, hope I can get an explanation so that I can pass it by.
I was running such a scenario from my code below:
public void sendBusinessEmail(communication.email.business.config.BusinessEmailList[] aEmailList)
{
System.Net.Mail.MailMessage objMsg = null;
string[] aEmail = null;
System.Net.Mail.SmtpClient objSmtpClient = null;
int iRetries = 0;
if (aEmailList == null)
{
return;
}
try
{
if (Properties.Settings.Default.IS_SMTP_TLS)
{
objSmtpClient = getSMTP_TLS_Client();
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
}
else
{
objSmtpClient = getSMTP_Default_Client();
}
foreach (communication.email.business.config.BusinessEmailList obj in aEmailList)
{
try
{
objMsg = new System.Net.Mail.MailMessage();
objMsg.From = new System.Net.Mail.MailAddress("jkstock#keells.com", "JKSB Business Services");
aEmail = obj.Emails;
if (Properties.Settings.Default.TO_TEST_EMAIL)
{
objMsg.To.Add(Properties.Settings.Default.TO_TEST_EMAIL_ADDRESS.ToString());
for (int i = 0; i < aEmail.Length; i++)
{
objMsg.Body += aEmail[i] + Environment.NewLine;
}
}
else
{
for (int i = 0; i < aEmail.Length; i++)
{
objMsg.To.Add(new System.Net.Mail.MailAddress(aEmail[i]));
}
objMsg.Body = obj.EmailBody;
}
objMsg.Subject = checkAllReadySent(obj.EmailSubject);
objMsg.Attachments.Add(new System.Net.Mail.Attachment(obj.AttachmentPath, (System.IO.Path.GetExtension(obj.AttachmentPath) == ".pdf" ? System.Net.Mime.MediaTypeNames.Application.Pdf : System.Net.Mime.MediaTypeNames.Application.Octet)));
//sending emails
//send for 5 times if error persists, unless otherwise success
for (int i = 0; i < 5; i++)
{
try
{
objSmtpClient.Send(objMsg);
obj.updateLog("OK", (i+1));
break;
}
catch (Exception e)
{
if (i == 4)
{
obj.updateLog(e.Message, (i+1));
}
}
}
objMsg = null;
}
catch (System.Net.Mail.SmtpFailedRecipientsException e0)
{
obj.updateLog("Invalid Recipient(s)",0);
}
catch (Exception e1)
{
obj.updateLog("Error",0);
}
}
objSmtpClient = null;
}
catch (Exception e2)
{
MessageBox.Show(e2.Message);
objMsg = null;
objSmtpClient = null;
}
}
References for the above code:
public abstract class BusinessEmailList
{
private string _accountid = string.Empty;
private string _attachmentPath = string.Empty;
private string _emailsubject = string.Empty;
private string _agentid = string.Empty;
private string _response = string.Empty;
private string _ccTo = string.Empty;
private string _bccTo = string.Empty;
protected string _additionalBody = string.Empty;
private string[] _aEmail = null;
public string AccountID
{
get { return _accountid; }
set { _accountid = value; }
}
public string AgentID
{
get { return _agentid; }
set { _agentid = value; }
}
public string Response
{
get { return _response; }
set { _response = value; }
}
public string AttachmentPath
{
get { return _attachmentPath; }
set
{
if (System.IO.File.Exists(value))
{
_attachmentPath = value;
}
else { throw (new Exception("Attachment Not Found")); }
}
}
public string EmailSubject
{
get { return _emailsubject; }
set { _emailsubject = value; }
}
public string[] Emails
{
get { return getEmail(); }
}
public string EmailBody
{
get { return getMsgBody(); }
set { _additionalBody = value; }
}
public string ccTo
{
get { return _ccTo; }
set { _ccTo = value; }
}
public string bccTo
{
get { return _bccTo; }
set { _bccTo = value; }
}
public virtual string[] getEmail()
{
return null;
}
public virtual string getMsgBody()
{
if (System.IO.Path.GetExtension(this.AttachmentPath) == ".pdf")
{
return "Dear Sir/Madam, " +
Environment.NewLine +
Environment.NewLine +
"With kind Reference to the above, details as per attachment." +
Environment.NewLine +
Environment.NewLine +
"To view the attached PDF files you need Adobe Acrobat Reader installed in your computer. Download Adobe Reader from http://get.adobe.com/reader/ " +
Environment.NewLine +
Environment.NewLine +
"Thank you," +
Environment.NewLine +
"John Keells Stock Brokers (Pvt) Ltd.";
}
else
{
return "Dear Sir/Madam, " +
Environment.NewLine +
Environment.NewLine +
"With kind Reference to the above, details as per attachment." +
Environment.NewLine +
Environment.NewLine +
"Thank you," +
Environment.NewLine +
"John Keells Stock Brokers (Pvt) Ltd.";
}
}
public void updateLog(string status, int retries)
{
try
{
using (OracleConnection oracleConn = new OracleConnection(EquityBroker32.Properties.Settings.Default.JKSB_CONN_ORA.ToString()))
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = oracleConn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "JKSBSCHEMA.EMAILLOG_ADD_PROC";
string[] aEmail = this.Emails;
OracleParameter p = null;
foreach (string s in aEmail)
{
cmd.Parameters.Clear();
p = new OracleParameter("pemail", OracleType.VarChar);
p.Value = s;
cmd.Parameters.Add(p);
p = new OracleParameter("psubject", OracleType.VarChar);
p.Value = this.EmailSubject;
cmd.Parameters.Add(p);
p = new OracleParameter("pattachement", OracleType.VarChar);
p.Value = this.AttachmentPath;
cmd.Parameters.Add(p);
p = new OracleParameter("presponse", OracleType.VarChar);
p.Value = status;
cmd.Parameters.Add(p);
p = new OracleParameter("pseqno", OracleType.Number);
p.Direction = ParameterDirection.InputOutput;
p.Value = "0";
cmd.Parameters.Add(p);
p = new OracleParameter("pretries", OracleType.Number);
p.Value = retries;
cmd.Parameters.Add(p);
oracleConn.Open();
cmd.ExecuteNonQuery();
oracleConn.Close();
}
}
}
catch (Exception er)
{
this.Response = er.Message;
}
}
}
public class BusinessClientEmailList : BusinessEmailList
{
public override string[] getEmail()
{
string[] aEmail;
//if (Properties.Settings.Default.TO_TEST_EMAIL == false)
//{
try
{
using (OracleConnection oracleConn = new OracleConnection(EquityBroker32.Properties.Settings.Default.JKSB_CONN_ORA.ToString()))
{
string sql = "SELECT EMAIL " +
"FROM " +
"(" +
"SELECT A.EMAIL AS EMAIL " +
"FROM JKSBSCHEMA.AGENTEMAIL A " +
"WHERE A.AGENTID = '" + this.AgentID + "' " +
"AND A.AGENTID != 'JKSB' "+
"AND A.ISACTIVE = 1 " +
"UNION " +
"SELECT B.EMAILID AS EMAIL " +
"FROM JKSBSCHEMA.CLIENTACCOUNTEMAIL B " +
"WHERE B.CLIENTACCOUNTID = '" + this.AccountID + "' " +
"AND B.IS_CONFIRMATION = 1 " +
") " +
"GROUP BY EMAIL";
int i = 0;
DataTable tbl = new DataTable();
OracleCommand cmd = new OracleCommand(sql, oracleConn);
cmd.CommandType = CommandType.Text;
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(tbl);
aEmail = new string[tbl.Rows.Count];
foreach (DataRow rw in tbl.Rows)
{
aEmail[i] = rw[0].ToString();
i++;
}
}
}
catch (Exception)
{
aEmail = null;
}
//}
//else
//{
// aEmail = new string[1];
// aEmail[0] = Properties.Settings.Default.TO_TEST_EMAIL_ADDRESS.ToString();
//}
return aEmail;
}
public override string getMsgBody()
{
return base.getMsgBody();
}
}