C# - First step with Amazon MWS - c#

I'm an Amazon FBA seller and I would like to begin to upload data regarding my sales in a more automated process using Amazon MWS. I just made an amazon MWS account and received my different IDs (Access Key Id, secret Access Key, ...).
I have the impression that most MWS developers use C#. I have a lot of Excel VBA experience but not in C#. Therefore, I'm not sure of the steps I have to follow.
On the webpage below, you can find a C# code that I would like to run:
http://www.samswiches.com/2011/02/how-to-use-amazon-mws-to-download-unshipped-order-reports/
Could you confirm the steps below are correct? :
1) Download Visual Studio => Do I need to download any extra package from Amazon?
2) In Visual Studio: File => New Project => C# console application
3) Erase all code and replace it by a copy-paste of the code found on above website => Do I need to put the code Inside something like "Sub - end Sub" in VBA?
4) Change "YourSecretKey", "YourSecretAccessKey", "YourSecretAccessKey", "YourMerchantID", "YourMarketplaceID" by my IDs.
5) Hit the run button
If it works, what will be the output like: An array inside Visual studio? A text file? A csv file? Where will it be stored?
I realize this is a very newbie question. However, I think that once I have a first code running correctly, my VBA experience will allow me to start efficiently from there.
Thanks in advance,
Diego.

After looking the code from http://www.samswiches.com/2011/02/how-to-use-amazon-mws-to-download-unshipped-order-reports/
I tried and changed something, and it works. Here is my solution:
Download the C# MWS Reports API Client Library: https://developer.amazonservices.com/doc/bde/reports/v20090101/cSharp.html
Use Visual Studio to create a project to get reports using MWS Reports API Client Library
Here is the code.
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
using MarketplaceWebService;
using MarketplaceWebService.Mock;
using MarketplaceWebService.Model;
using System.IO;
using System.Threading;
public void testReport()
{
String accessKeyId = "Your Access Key ID";
String secretAccessKey = "Your Secret Access Key";
const string merchantId = "Merchant ID";
const string marketplaceId = "Marketplace ID";
MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();
config.ServiceURL = "https://mws.amazonservices.com";
const string applicationName = "ApplicationName";
const string applicationVersion = "0.01";
MarketplaceWebServiceClient service =
new MarketplaceWebServiceClient(
accessKeyId,
secretAccessKey,
applicationName,
applicationVersion,
config);
RequestReportRequest reportRequestRequest = new RequestReportRequest();
reportRequestRequest.Merchant = merchantId;
// you can change ReportType here:
//http://docs.developer.amazonservices.com/en_IN/reports/Reports_ReportType.html
reportRequestRequest.ReportType = “_GET_FLAT_FILE_ACTIONABLE_ORDER_DATA_";
RequestReportResponse requestResponse = service.RequestReport(reportRequestRequest);
IdList lstRequestID = new IdList();
lstRequestID.Id.Add
(requestResponse.RequestReportResult.ReportRequestInfo.ReportRequestId);
GetReportRequestListRequest reportRequestListRequest = new
GetReportRequestListRequest();
reportRequestListRequest.Merchant = merchantId;
reportRequestListRequest.ReportRequestIdList = lstRequestID;
List<ReportRequestInfo> myListzz = new List<ReportRequestInfo>();
GetReportRequestListResponse reportRequestListResponse = new
GetReportRequestListResponse();
reportRequestListResponse =
service.GetReportRequestList(reportRequestListRequest);
GetReportRequestListResult reportRequestListResult = new
GetReportRequestListResult();
reportRequestListResult =
reportRequestListResponse.GetReportRequestListResult;
myListzz = reportRequestListResult.ReportRequestInfo;
if (myListzz.Count > 0)
{
while (myListzz[0].ReportProcessingStatus.ToString() != "_DONE_")
{
Console.WriteLine("Waiting for Report");
Thread.Sleep(61000);
reportRequestListResponse =
service.GetReportRequestList(reportRequestListRequest);
reportRequestListResult =
reportRequestListResponse.GetReportRequestListResult;
myListzz = reportRequestListResult.ReportRequestInfo;
}
if (myListzz[0].GeneratedReportId !=null)
{
GetReportRequest reportRequest = new GetReportRequest();
reportRequest.Merchant = merchantId;
String source = "C:\\myreport.txt";
reportRequest.ReportId = myListzz[0].GeneratedReportId;
reportRequest.Report = File.Open(source, FileMode.Create,
FileAccess.ReadWrite);
service.GetReport(reportRequest);
}
}
}

You are missing step 1b) Download the C# MWS Reports API Client Library. You may need other libraries to access other parts of the MWS API, but from a quick glance at that code above library is the main one.
Note that it refers to a lblStatus, which seems to be a label on a form, but nowhere in that post does it say anything else about that form. So step 2) probably is not a "console" style application, but a form based one, which also means, you shouldn't erase all code in step 3, but paste the code into whatever is the equivalent of a main() function (I've only ever used C and C++, but not C#, so I have no clue)

Related

.NET Core vs .NET Framework, My code works in as part of .NET Core but doesn't as part of .NET framework, Why?

I am very new to the C# and .NET stuff and been experimenting with some HTML parsing and file downloading when i came across a problem.
I had previously written my code in .NET Core and it was working fine and then i realised that i need to use System.Windows.Forms to be able to access User's monitor resolution and tried transfering my code to .NET framework app to be able to add the System.Windows.Forms assembly (Apparently it is not possible in .NET Core, Please let me know if I am wrong 😁).
So Here is the code:
using System;
using System.Linq;
using HtmlAgilityPack;
using System.Net;
using System.IO;
namespace AmazingSuperAwesomeWallpaperDownloaderAppConsoleApp
{
class Program
{
static void Main(string[] args)
{
Download();
}
static void Download()
{
Console.WriteLine("Please enter the wallpaper page ID: ");
//Asks for user to input the Wallpaper ID and creates the link out of it.
var userInput = "https://SuperSecretWallpaperWebsite.com/Wallpapers/" + Console.ReadLine();
// set the html var to the website link to parse
var html = #userInput;
//gets the website html from the HTTP
HtmlWeb web = new HtmlWeb();
//Creates a var called document to load the wesite in it.
var document = web.Load(html);
var fileName = "Wallpaper.jpg";
//Creates a container, the first div to pass a certain criteria for the container will populate this container
var container = document.DocumentNode.Descendants("div").FirstOrDefault(x => x.Attributes.Contains("class") && x.Attributes["class"].Value == "wallpaperContainer");
if (container != null)
{
//Does the same thing as above and looks for the Div with details class and stores it in the title var.
var titleContainer = container.Descendants("div").FirstOrDefault(x => x.Attributes.Contains("class") && x.Attributes["class"].Value == "details");
if (title != null)
{
//Finds the first h1 tag that is in title var and stores it in titlevalue
var titleValue = titleContainer.Descendants("h1").FirstOrDefault();
if (titleValue != null)
{
//A var that is set to the innter text of the the h1 that was found in the titleValue var.
var h1TitleValue = titleValue.InnerText;
//Adds file extension to the file name which is the title
fileName = h1TitleValue + ".jpg";
Console.WriteLine("Title: " + h1TitleValue);
}
}
}
//Creates aTag container, the first aTag to pass a certain criteria for the container will populate this container
var aTagContainer = document.DocumentNode.Descendants("a").FirstOrDefault(x => x.Attributes.Contains("class") && x.Attributes["class"].Value == "downloadButton" && x.Attributes.Contains("href"));
if (aTagContainer != null)
{
//Splits the wallpaper URL from the rest of the useless url stuff
var DLink = aTagContainer.Attributes["href"].Value.Split("Url=");
using (var client = new WebClient())
{
//Finds the MyPictures folder for the logged in user and sets it to the wallpaper directory
var filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "SuperAwesomeWallpaperDownloadFolder\\");
//Creates the folder in MyPicture folder
System.IO.Directory.CreateDirectory(filePath);
//Downloads the wallpaper file and saves it in the directory
client.DownloadFile(DLink[1], (filePath + fileName));
Console.WriteLine(filePath);
}
Console.WriteLine("Download Link is: " + DLink[1]);
}
}
}
}
After copying and pasting the code in a new Console app with .NET framework I get errors in
var DLink = aTagContainer.Attributes["href"].Value.Split("Url=");
saying that inside Split it should be a Char and not a string! then why did it work in .NET Core?
client.DownloadFile(DLink[1], (filePath + fileName));
Also the Download function seems to not like the way it is set up for some reason and will not work no matter what despite working fine in .NET Core.
Also I know my code is probably not as well-written, I would be happy to hear your criticism regarding that as well.
Thank you in advance kind stranger 🥰
in .net core 2.0 and above, there is an overload for split which takes a string as input however this is not the case in .net framework which takes a character for split. If you want to split a string based on another string use the sample code mentioned below.
var DLink = aTagContainer.Attributes["href"].Value
.Split(new string[] { "Url=" }, StringSplitOptions.None);
Hope it helps.

LINQPad missing dll for Grpc

I am trying to test some methods in my library using Google API. More specifically the Cloud Vision API. When I reference the library in LINQPad I get an error
FileNotFoundException: Error loading native library. Not found in any of the possible locations: C:\Users\\AppData\Local\Temp\LINQPad5_dgzgzeqb\shadow_fxuunf\grpc_csharp_ext.x86.dll,C:\Users\\AppData\Local\Temp\LINQPad5_dgzgzeqb\shadow_fxuunf\runtimes/win/native\grpc_csharp_ext.x86.dll,C:\Users\\AppData\Local\Temp\LINQPad5_dgzgzeqb\shadow_fxuunf../..\runtimes/win/native\grpc_csharp_ext.x86.dll
I have tried copying the dll into all of these locations as well as my LINQPad Plugins and the LINQPad folder. I have tried clearing Cancel and Clear query thinking I needed to reset it. I have also closed and reopened LINQPad thinking maybe it re-scans the directory on load. None of this has worked. Has LINQPad changed where to put dlls or am I missing something?
I am using Google.Cloud.Vision.V1
`
var file = new byte[128];
var _settingsCon = new SettingConnector();
var apiKey = Task.Run(() => _settingsCon.Get("Google:Key")).Result.Value;
var credential = Google.Apis.Auth.OAuth2.GoogleCredential.FromJson(apiKey);
var channel = new Grpc.Core.Channel(
ImageAnnotatorClient.DefaultEndpoint.ToString(),
credential.ToChannelCredentials());
var builder = new StringBuilder();
var image = Image.FromBytes(file);
var client = ImageAnnotatorClient.Create(channel);
var response = client.DetectDocumentText(image);
foreach (var page in response.Pages)
{
foreach (var block in page.Blocks)
{
foreach (var paragraph in block.Paragraphs)
{
builder.Append(paragraph);
}
}
}
builder.ToString().Dump();`
This is essentially the function. The file is a dummy file that would be passed in. It shouldn't matter cause it can't make the request any way. The Dump is used instead of return.

CoolUtils TotalPDFPrinterX causes ASP C# site to crash

My company has purchased the CoolUtils TotalPDFPrinterX from https://www.coolutils.com/TotalPDFPrinterX
I make an HTTP PUT from Postman to the API and I get “Could not get any response”.
When running on my Windows machine the PDF prints fine however on the server the site crashes and in the event log I get the error "A process serving application pool '[MY_APP_POOL]' failed to respond to a ping. The process id was '[MY_PROCESS_ID]'."
Here is my C# code:
PDFPrinterX ppx = new PDFPrinterX();
ppx.Print(fileName, printerName, "-ap Default");
if (ppx.ErrorMessage != null)
{
WriteToSQL(id, false, ppx.ErrorMessage, 2);
Console.WriteLine(ppx.ErrorMessage);
}
By writing to the event log I know the site crashes on this line: PDFPrinterX ppx = new PDFPrinterX(); I have also surrounded the above code with a try catch and no exception is thrown. The site still crashes.
Things I have tried:
Uninstalling and Reinstalling the CoolUtils software
Giving EVERYONE Full control to the site folder and the CoolUtils program folder
Creating a C# desktop application using the same code. THIS WORKS FINE ON THE SERVER. It's just the ASP site that crashes.
Does anyone know what might be causing this?
The more I research this thing online the more I'm inclined to say that ActiveX which is the X in PDFPrinterX doesn't seem to work well when hosted in IIS.
I've seen a few forums where they say it works fine when they debug on localhost but when deployed to server is crashes.
...works fine when used inside localhost(Visual studio)
One of their feature pages shows that it requires Win 2000/NT/XP/2003/Vista/7
You should look into whether your server supports ActiveX components that can work in conjunction with IIS.
Looking at one of their other products support page: TotalPDFConverterX:
the following note in my opinion may also apply to TotalPDFPrinterX, given its dependency on ActiveX as well.
Note: Pay attention to some details during installation Total PDF Converter X:
Do not forget to register ActiveX in your web-server account.
Total PDF Converter X supports only Internet Explorer, Mozilla and Firefox browsers.
ActiveX works only with 32-bit internet information server. 64-bit server is not supported. Use command line version instead.
Thanks to #Nkosi I was able to find a workaround.
ActiveX works only with 32-bit internet information server. 64-bit server is not supported. Use command line version instead.
Our IIS server is 64 bit so that is what probably caused the site to hang up.
Buttt... the command line still worked in printing the PDFs on the server.
Client side code (makes the HTTP POST):
private void SendToPrinter(string fileName, string printerName, int id, decimal documentSequence)
{
// use http client to make a POST to the print api
using (var client = new HttpClient())
{
// compile the values string to transfer in POST
// should finish to look something like this:
// C:\print.pdf&PRTFTW_OFIT&ValShip-155320-1
var values = new Dictionary<string, string>
{
{ "", fileName + "&" + printerName + "&ValShip-" + id + "-" + documentSequence},
};
// URL encode the values string
var content = new FormUrlEncodedContent(values);
// make the POST
// DEBUG
var response = client.PostAsync("http://localhost:54339/api/print", content);
// retrieve the response
var responseString = response.Result.ToString();
}
}
Server side code (receives the HTTP POST):
using System;
using System.Net.Http;
using System.Web;
using System.Web.Http;
namespace api.valbruna.print.Controllers
{
public class PrintController : ApiController
{
// POST api/print
public HttpResponseMessage Post(HttpRequestMessage request)
{
try
{
// parse the content recieved from the client
var content = request.Content.ReadAsStringAsync().Result;
// decode the content, certain characters such as
// '&' get encoded to URL lingo such as '%26'
content = HttpUtility.UrlDecode(content);
// split the string into 3 seperate parts
String[] str = content.Split('&');
// remove the equal sign from the first string
str[0] = str[0].Trim('=');
// compile the arguments command line string
// should finish to look something like this:
// "C:\Program Files (x86)\CoolUtils\Total PDF PrinterX\PDFPrinterX.exe" "C:\print.pdf" -p"\\PRINTERS\PRTFTW_OFIT" -ap Default -log "C:\inetpub\logs\CoolUtils\log-ValShip-155320-4.txt" -verbosity detail"
String arguments = "\"" + str[0] + "\" -p\"\\\\PRINTERS\\" + str[1] +
"\" -ap Default -log \"C:\\inetpub\\logs\\CoolUtils\\log-" + str[2] +
".txt\" -verbosity detail";
// file location for PDFPrinterX.exe
String file = #"C:\Program Files (x86)\CoolUtils\Total PDF PrinterX\PDFPrinterX.exe";
// start the process
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = file;
startInfo.Arguments = arguments;
process.StartInfo = startInfo;
process.Start();
return new HttpResponseMessage() { Content = new StringContent(content) };
}
catch (Exception e)
{
return new HttpResponseMessage() { Content = new StringContent(e.Message) };
}
}
}
}

Download file from opensubtitles.org

I need to download files from opensubtitles.org trough my application which is written in GTK# and C#. The app is based on .NET 4.0 framework.
At first this was the code I was using:
var tZip = new FastZip();
try {
var tRequest = (HttpWebRequest)HttpWebRequest.Create(tDownloadUrl);
var tZipResponse = (HttpWebResponse)tRequest.GetResponse();
using (var tStream = tZipResponse.GetResponseStream()) {
using (var tMemStream = new MemoryStream()) {
tStream.CopyTo(tMemStream);
var tTempPath = Globals.video_location + "OSD";
Directory.CreateDirectory(tTempPath);
tZip.ExtractZip(tMemStream, tTempPath, FastZip.Overwrite.Always, null, #"\.srt$", null, false, true);
var tDirInfo = new DirectoryInfo(tTempPath);
var tFileInfo = new FileInfo(Globals.location_video);
var tSrtFile = tDirInfo.EnumerateFiles().FirstOrDefault();
if (tSrtFile == null) {
writeLog("No .srt file found in zip..");
goto text;
}
writeLog("Downloaded and unpacked: " + tSrtFile.Name);
File.Copy(tSrtFile.FullName, Globals.video_location+Globals.video_name+".srt", true);
Globals.savedTitle = Globals.video_location+Globals.video_name+".srt";
// clean up..
Directory.Delete(tTempPath, true);
writeLog("Deleted temp folder.");
return true;
}
}}
And that worked really well up until few days ago, now it is returning a bunch of html code instead of .zip file. I tried even something like this:
WebClient client = new WebClient();
client.DownloadFile(link, #"OSD\test.zip");
But everything just keeps returning bunch of html code.
The link I am usually trying to download is something like this:
http://dl.opensubtitles.org/en/download/subad/4287952
If you click on the link above it will just redirect you to the opensubtitles.org page of that particular subtitle. But if you right mouse click on that link and then select "open in new tab" or "open in new window" it will automatically start the download. (Tested in Firefox)
Also as soon as I paste that link in "Internet Download Manager" application, it will start the download of the zip file automatically.
If you can help me to resolve this problem I will truly be grateful.
Kind Regards.
I got into this problem because I was filtering the website xml directly. Like from a link such as this one: opensubtitles.org example
And in the beginning it used to work well, but then they changed something on the website and it stopped working. So what I did was build on top of this: OSHandler
That handler library is using XML-RPC so I believe there won't be any problems in the future.

Using FaxComEx library?

I'm trying to write a program that will send faxes to the Windows Fax system but I am having problems with the COM library FaxComEx.
My code:
try
{
var faxServer = new FAXCOMEXLib.FaxServer();
var faxDoc = new FAXCOMEXLib.FaxDocument();
faxServer.Connect("");
faxDoc.Body = #"C:\\test.txt";
faxDoc.Recipients.Add("5551212", "Recipient");
faxDoc.ConnectedSubmit(faxServer);
}
is supposed to work, but it fails whenever I try to send a fax and I'm not sure why. Any ideas?
You are using both a literal qualifier and an escape character. You should just use one or the other.
You should try one of the following.
faxDoc.Body = #"C:\test.txt";
or
faxDoc.Body = "C:\\test.txt";

Categories

Resources