How to consume web post service in C#? I did tests with POSTMAN and I got a response data, but in .net my response is empty. It works great in PostMan. The problem is how to format the Body Content and send it.
string idop = "";
List<ProductJSON> listProductsJSON = new List<ProductJSON>();
List<List<string>> productJSON = new List<List<string>>();
List<string> products = new List<string>();
products.Add("4");
products.Add("5");
products.Add("30.2");
products.Add("1");
products.Add("0");
products.Add("4");
productJSON.Add(products);
using (var client = new HttpClient())
{
var res = client.PostAsync("http://xyz.cti.lat/sant2/webservices/edd.php",
new StringContent(JsonConvert.SerializeObject(
new {
a = "pCatlog",
cnal = "RED",
tpo = "2",
fpago = "DETO",
pgdo = "0",
rc = "13123",
local = "BACK",
localorg = "BACK",
raz = "PPPPPP",
dir_ruc = "name",
log = "CREAVIR",
not = "DETO2",
del = "0",
dir = "",
ubi = "",
refe = "",
prod = productJSON
}),
Encoding.UTF8, "application/json")));
try
{
res.Result.EnsureSuccessStatusCode();
var x = res;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Can you try this code inside of the try block?
if (res.IsCompleted)
{
var result = res.Result;
var response = result.Content.ReadAsStringAsync();
var data = response.Result;
}
The ideal would be to declare this as an async method and use the await operations to get the result as follows.
var res = await client.PostAsync(<url>, <string_content>);
var result = await res.Content.ReadAsStringAsync();
Related
I have written a test for edit model of a class in EF core.
public async Task<Expense> EditExpense(Expense model)
{
var expense = _dataRepository.Where<Expense>(x => x.Id == model.Id).ToList();
if(expense != null)
{
expense.ForEach(x =>
{
x.Name = model.Name;
x.AddedOn = model.AddedOn;
x.Amount = model.Amount;
x.Type = model.Type;
x.SplitOption = model.SplitOption;
x.Notes = model.Notes;
x.IsGroupExpense = model.IsGroupExpense;
});
return expense.FirstOrDefault();
}
else
{
return null;
}
}
I want to test this method using xUnit and Moq and I have also written a method for it as below.
[Fact]
public async void UnitTest_IsExpenseEdited_ReturnsTrue()
{
var expenseCurrent = new Expense()
{
Id = 5,
Name = "Test Expense",
Amount = 1500,
AddedBy = "44db32c3-ad6a-4d68-a683-862be363f59c",
AddedOn = DateTime.Now,
Notes = "",
IsDeleted = false,
IsGroupExpense = false,
SplitOption = 1,
Type = 0
};
var expenseList = (new List<Expense>{ expenseCurrent });
var expenseAfterEdit = new Expense()
{
Id = 5,
Name = "Test Expense Edited",
Amount = 2000,
AddedBy = "44db32c3-ad6a-4d68-a683-862be363f59c",
AddedOn = DateTime.Now,
Notes = "Edited !!!",
IsDeleted = false,
IsGroupExpense = true,
SplitOption = 2,
Type = 0
};
_dataRepositoryMock.Setup(x => x.Where<Expense>(a => a.Id == expenseCurrent.Id)).Returns(expenseList as IQueryable<Expense>);
var expenseEdited = await _exepenseRepository.EditExpense(expenseAfterEdit);
Assert.Equal(expenseEdited, expenseAfterEdit);
}
But here, the Where method is returning null
public async Task<Expense> EditExpense(Expense model)
{
var expense = _dataRepository.Where<Expense>(x => x.Id == model.Id).ToList(); in repository
}
I am getting var expense null in above code.
Please suggest what should I include in the code to get the value in above var expense?
To test this method, I want to create a fake data which is going to be updated. Please suggest how this thing needs to be written properly?
How Can I call the Request Get (Api) from server side.
Here is the Server side
public string GetAllBook()
{
bookAssembly bookassembleur = new bookAssembly();
bookList = bookassembleur.GetBooks();
}
And here is the Api Request
public List<Book> Get()
{
BookAssembly searchallbook = new BookAssembly();
return searchallbook.GetBooks();
bookAssembly bookassembleur = new bookAssembly();
bookList = bookassembleur.GetBooks();
DataTable dt = new DataTable();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("ID");
dt.Columns.Add("Title");
dt.Columns.Add("Price");
dt.Columns.Add("Author");
dt.Columns.Add("Qauntite");
dt.Columns.Add("Categorie");
}
foreach (Book book in bookList)
{
DataRow NewRow = dt.NewRow();
NewRow[0] = book.ID;
NewRow[1] = book.Title;
NewRow[2] = book.Price;
NewRow[3] = book.Author;
NewRow[4] = book.Qauntite;
NewRow[5] = book.Categorie.Name;
dt.Rows.Add(NewRow);
}
gvBook.DataSource = dt;
gvBook.DataBind();
return "";
}
i want remove bookList = bookassembleur.GetBooks() ana call api
You have to access it using HttpClient.
e.g.
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("<your_api_path>");
var response= client.GetAsync("GetAllBook");
response.Wait();
BookAssembly searchallbook = response.Result;
}
P.S. this is not running code, just an idea.
public string GetAllBook()
{
DataTable dt = new DataTable();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:6735/api/book");
//HTTP GET
var responseTask = client.GetAsync("Book");
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<Book[]>();
readTask.Wait();
var Books = readTask.Result;
if (dt.Columns.Count == 0)
{
dt.Columns.Add("ID");
dt.Columns.Add("Title");
dt.Columns.Add("Price");
dt.Columns.Add("Author");
dt.Columns.Add("Qauntite");
dt.Columns.Add("Categorie");
}
foreach (Book book in Books)
{
DataRow NewRow = dt.NewRow();
NewRow[0] = book.ID;
NewRow[1] = book.Title;
NewRow[2] = book.Price;
NewRow[3] = book.Author;
NewRow[4] = book.Qauntite;
NewRow[5] = book.Categorie.Name;
dt.Rows.Add(NewRow);
}
}
}
gvBook.DataSource = dt;
gvBook.DataBind();
return "";
}
I have implemented a small PayPal PLUS Demo in ASP.NET:
protected void Page_Load(object sender, EventArgs e)
{
var config = ConfigManager.Instance.GetProperties();
config.Add("clientId", "XXXXXXXXXXXXXXXXXXXXXXXXX");
config.Add("clientSecret", "XXXXXXXXXXXXXXXXXXXXXXXXX");
config.Add("mode", "sandbox");
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
var apiContext = new APIContext(accessToken);
var itemList = new ItemList() { items = new List<Item>() { new Item() { name = "Item Name", currency = "USD", price = "15", quantity = "5", sku = "sku" } } };
var payer = new Payer() { payment_method = "paypal" };
var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?";
var guid = Convert.ToString((new Random()).Next(100000));
var redirectUrl = baseURI + "guid=" + guid;
var redirUrls = new RedirectUrls() { cancel_url = redirectUrl + "&cancel=true", return_url = redirectUrl };
var details = new Details() { tax = "15", shipping = "10", subtotal = "75" };
var amount = new Amount() { currency = "USD", total = "100.00", details = details };
var transactionList = new List<Transaction> { new Transaction() { description = "Transaction description.", invoice_number = new Random().Next(999999).ToString(), amount = amount, item_list = itemList } };
var payment = new Payment() { intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrls };
var createdPayment = payment.Create(apiContext);
var approval_url = createdPayment.links.FirstOrDefault(x => x.rel == "approval_url").href;
hfApprovalUrl.Value = approval_url;
}
<asp:HiddenField runat="server" id="hfApprovalUrl"/>
<script src="https://www.paypalobjects.com/webstatic/ppplus/ppplus.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="ppplus"></div>
<script type="application/javascript">
var approval_url = $('#hfApprovalUrl').val();
var ppp = PAYPAL.apps.PPP({
"approvalUrl": approval_url,
"placeholder": "ppplus",
"mode": "sandbox",
"country": "DE"
});
</script>
Its works so far but if a choose a pay option (e.g. credit card) I will be redirected to PayPal.I want that the user stys on my own page. How can I do this?
Thanks!
Jan
I am trying this code for creating new campaign using MailChimp API in ASP.NET
public string CreateCampaignAndSend(string apiKey, string listID)
{
Int32 TemplateID = 100;
string campaignID = string.Empty;
MailChimpManager mc = new MailChimpManager("sampleAPIKeyXXXXXXXXXXXXXX-us12");
// compaign Create Options
campaignCreateOptions campaignCreateOpt = new campaignCreateOptions();
campaignCreateOpt.list_id = listID;
campaignCreateOpt.subject = "subject";
campaignCreateOpt.from_email = "wisdomthnkrs#gmail.com";
campaignCreateOpt.from_name = "abc";
campaignCreateOpt.template_id = TemplateID;
campaignCreateOpt.authenticate = true;
campaignCreateOpt.auto_footer = false;
campaignCreateOpt.tracking.opens = true;
campaignCreateOpt.tracking.html_clicks = true;
campaignCreateOpt.tracking.text_clicks = true;
// 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
campaignCreateParms campaignCreateParms = new campaignCreateParms(mc.APIKey, EnumValues.campaign_type.regular, campaignCreateOpt, content, csOptions, typeOptions);
campaignCreateInput campCreateInput = new campaignCreateInput(campaignCreateParms);
campaignCreate campaignCreate = new campaignCreate(campCreateInput);
//xyz();
//string abc = xxxxxxxxxxxxxxxxx;
campaignCreateOutput ccOutput = campaignCreate.Execute(campCreateInput);
List<Api_Error> error = ccOutput.api_ErrorMessages; // Catching API Errors
string s = "null";
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);
s = s + ae.code;
s = s + ae.error;
}
}
return s;
}
but it shows an error while I am giving the right key.
here is the error,
null104Invalid MailChimp "Invalid MailChimp API key:
6ea29f158xxxxxxxxxxxx"
This problem is driving me nuts... I don't know how to fix it. I'm trying to create an inventory movement journal entry using the ProfitLossJournalService.
The code below runs, but it shows the transaction in the "inventory adjustment" journal. I want it in the inventory movement jounal.
public void UpdateInventoryForConsumableItem(InventoryUpdate update)
{
var svc = new ProfitLossJournalServiceClient();
var cc = new CallContext {Company = "SS"};
var journal = new AxdProfitLossJournal();
var table = new AxdEntity_InventJournalTable
{
InventDimFixedSpecified = false,
InventSiteId = "MC",
InventLocationId = "MAIN WH",
JournalType = AxdEnum_InventJournalType.Movement,
JournalNameId = "InvMovJour",
Description = Constants.InventoryMovementJournalDescription,
NumOfLines = 1,
NumOfLinesSpecified = true,
JournalTypeSpecified = true,
JournalId = "InvMovJour",
JournalIdOrignal = "InvMovJour",
action = AxdEnum_AxdEntityAction.update
};
var inventoryDims = new AxdEntity_InventDim
{
InventLocationId = "MAIN WH",
InventDimId = update.InventoryDimId,
InventColorId = update.Color,
InventSiteId = "MC",
InventSizeId = update.Size,
InventStyleId = update.Style,
action = AxdEnum_AxdEntityAction.create
};
var entry = new AxdEntity_InventJournalTrans
{
InventDimId = update.InventoryDimId,
TransDate = DateTime.Now,
ItemId = update.ItemId,
CostMarkupSpecified = false,
InventRefTypeSpecified = false,
LineNumSpecified = false,
JournalType = AxdEnum_InventJournalType.Movement,
JournalTypeSpecified = true,
Qty = update.Quantity,
QtySpecified = true,
InventDim = new AxdEntity_InventDim[1] {inventoryDims}
};
table.InventJournalTrans = new[] {entry};
journal.InventJournalTable = new[] {table};
try
{
var result = svc.create(cc, journal);
Logger.LogTrace(string.Format("sending InventoryTransferJournal {0}", result.GetValue(0)));
Logger.LogEvent(Logger.SentConsumableInventoryUpdateToDynamics);
}
catch (Exception e)
{
Logger.LogException(e);
throw;
}
}
When you use the ProfitLossJournalService that is essentially what you are creating, an Inventory adjustment.
If you want to create an inventory movement journal, unfortunately there is no standard AIF service that does that. You would need to implement that yourself and expose it to AIF.