POST data using POSTMAN - c#

so I've been having trouble using the POST method with C# and POSTMAN.
The GET works pretty fine but I'm getting an error on the POST method.
Here's my code:
public SaveProfileResponseDTO SaveProfileQuery(SaveProfileRequestDTO objProfileRequest)
{
SaveProfileResponseDTO objSaveProfileResponse;
try
{
XElement xElement = XElement.Load(Path);
XElement Student = (from u in xElement.Elements("Student")
where (string)u.Attribute("id") == objProfileRequest.StudentID.ToString()
select (u)).FirstOrDefault();
Student.Element("Name").Value = objProfileRequest.Name;
Student.Element("Gender").Value = objProfileRequest.Gender;
xElement.Save(Path);
objSaveProfileResponse = new SaveProfileResponseDTO()
{
Status = new ResponseCode()
{
Code = StatusCodes.Success,
Message = StatusMessages.Success
}
};
}
catch (Exception ex)
{
objSaveProfileResponse = new SaveProfileResponseDTO()
{
Status = new ResponseCode()
{
Code = StatusCodes.Error,
Message = StatusMessages.Error
}
};
}
return objSaveProfileResponse;
}
This is my Controller:
[Route("Profile")]
[HttpPost]
public HttpResponseMessage Profile(SaveProfileRequestModel objSaveProfileRequestModel)
{
StudentManager = new StudentManager();
SaveProfileRequestDTO objSaveProfileRequestDTO = new SaveProfileRequestDTO()
{
Gender = objSaveProfileRequestModel.Gender,
Name = objSaveProfileRequestModel.Name,
StudentID = objSaveProfileRequestModel.StudentID
};
SaveProfileResponseDTO objSavePofileResponse = StudentManager.SaveProfile(objSaveProfileRequestDTO);
SaveProfileResponseModel objSaveProfileResponseModel = new SaveProfileResponseModel()
{
Status = objSavePofileResponse.Status
};
return Request.CreateResponse(HttpStatusCode.OK, objSavePofileResponse);
}
Any help would be appreciated.
I can also provide the GET method code if you want.
Thank you in advance.

XElement Student = (from u in xElement.Elements("Student")
where (string)u.Attribute("id") == objProfileRequest.StudentID.ToString()
select (u)).FirstOrDefault();
Student.Element("Name").Value = objProfileRequest.Name;
This last line will cause a NullReferenceException if there is no student in the XML file matching the ID you're passing in.

Related

How to filter SOAP results client side in C#?

I make SOAP requests to an e-commerce API to know how many orders were made for a specified product, in a given time frame.
My method takes a product ID and a number of days to create a time frame. Then it constructs a SOAP request and returns the amount sold products.
public static async Task<int?> GetOrdersFromApi(int providedId, int days) {
var dateFrom = DateTime.Now.AddDays(days * -1).ToString("yyyy-MM-dd") + " 00:00:00";
var dateTo = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
float orderedCount = 0;
int orderedCountToPass = 0;
int i = 0;
var binding = new BasicHttpBinding {
MaxReceivedMessageSize = 40000000
};
var address = new EndpointAddress("http://example.com/api/get/");
using (var client = new ApiOrdersPortTypeClient(binding, address)) {
try {
while (true) {
// request parameters
var request = new ApiOrdersGetAsync.requestType {
authenticate = new ApiOrdersGetAsync.authenticateType {
userLogin = "Username",
authenticateKey = "Key",
}
};
request.#params = new ApiOrdersGetAsync.paramsType {
ordersStatuses = new string[] { "finished" },
products = new productType[1],
};
request.#params.products[0] = new productType {
productIdSpecified = true,
productId = providedId,
};
request.#params.ordersRange = new ordersRangeType {
ordersDateRange = new ordersDateRangeType()
};
request.#params.ordersRange.ordersDateRange.ordersDateTypeSpecified = true;
request.#params.ordersRange.ordersDateRange.ordersDateType = ordersDateTypeType.dispatch;
request.#params.ordersRange.ordersDateRange.ordersDateBegin = dateFrom;
request.#params.ordersRange.ordersDateRange.ordersDateEnd = dateTo;
request.#params.resultsPageSpecified = true;
request.#params.resultsPage = i;
// processing the result
var results = await client.getAsync(request);
foreach (var result in results.Results) {
int productsResultsPage = 0;
foreach (var product in result.orderDetails.productsResults) {
try {
if (result.orderDetails.productsResults[productsResultsPage ].productId == providedId) {
orderedCount += result.orderDetails.productsResults[y].productQuantity;
productsResultsPage++;
}
} catch (IndexOutOfRangeException ex) {
// error is thrown to escape loop - sloppy, I know
Console.WriteLine(ex);
};
}
};
orderedCountToPass = (int)orderedCount;
orderedCount = 0;
i++;
};
} catch (NullReferenceException) {
// do nothing, we just want to exit while loop when i is higher than page count
}
return orderedCountToPass;
};
}
The result often should be in hundreds, but regardless how well a product sells, it returns something from 0 to 4.
Here is a sample response:
For example, I'm only interested with productId == 479, but an order was made with other products as well that don't interest me - I need to filter them.
I'm doing something wrong with how I try to filter results. How do I do it properly? I'm certain the request is correct and response does contain all possible orders.
You are getting xml results so use Net Xml library :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string URL = #"Enter URL Here";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(URL);
List<XElement> items = doc.Descendants("item").ToList();
}
}
}

To know reason of not added record in NetSuite

Trying to add new customer to NetSuite like it described in sample in manual.
private static void Main(string[] args)
{
ApplicationInfo _appInfo;
var service = new NetSuiteService();
service.CookieContainer = new CookieContainer();
_appInfo = new ApplicationInfo();
_appInfo.applicationId = "FB31C4F2-CA6C-4E5F-6B43-57632594F96";
service.applicationInfo = _appInfo;
var passport = new Passport();
passport.account = "5920356_SB9";
passport.email = "a#a.com";
var role = new RecordRef();
role.internalId = "3";
passport.role = role;
passport.password = "#sdkkr_5543";
try
{
var status = service.login(passport).status;
}
catch (Exception e)
{
Console.Out.WriteLine(e.Message);
throw;
}
var cust = new Customer();
cust.entityId = "XYZ Inc";
cust.altEmail = "aaa#aaa.aaa";
var response = service.add(cust);
Console.Out.WriteLine("response.status.isSuccess " + response.status.isSuccess) ;
Console.Out.WriteLine("response.status.isSuccessSpecified " + response.status.isSuccessSpecified);
service.logout();
}
As result I got:
response.status.isSuccess False
response.status.isSuccessSpecified True
I suppose customer was not inserted. What is wrong and how to know that?
When you call add() on the service, the response contains a status property which contains a statusDetail property. statusDetail is an array of the messages (warnings and errors) that resulted from your add(). You can loop through these to find out why saving your customer record was unsuccessful:
var response = service.add(cust);
if (!response.status.isSuccess)
{
foreach (var error in response.status.statusDetail)
{
Console.WriteLine($"Error creating customer: {error.type} {error.message}");
}
}

How to Update campaign in Bing Ads?

For Update campaign I am using this Code
public async Task<List<long?>> updateCampaign(Campaign campaign,string status)
{
try
{
campaign.Status = (CampaignStatus)(int)Enum.Parse(typeof(CampaignStatus), status);
var request = new UpdateCampaignsRequest
{
Campaigns = new Campaign[] { campaign },
CustomerId = "xxxxxx",
UserName = "something#outlook.com",
Password = "something#123",
ApplicationToken = "myApplicationToken",
CustomerAccountId = "123456",
DeveloperToken = "1234567890"
};
CampaignService = new ServiceClient<ICampaignManagementService>(_authorizationData);
CampaignService.RefreshOAuthTokensAutomatically = false;
var result = (await CampaignService.CallAsync((s, r) => s.UpdateCampaignsAsync(r), request));
if (result.TrackingId != null)
{
return result.CampaignIds.ToList();
}
else
{
return new List<long?>();
}
}
catch (Exception ex)
{
ErrorLog.log(ex);
return new List<long?>();
}
}
When I run this code, I got this error "Invalid client data. Check the SOAP fault details for more information"
thanks.
For updating the Campaign we can use "BulkServiceManager" for bulk updating of the campaign,you can use this service single campaign update also.
public async Task<List<long?>> updateCampaign(List<Campaign> campaigns)
{
try
{
var listBulkCampaign = new List<BulkCampaign>();
foreach (var campaign in campaigns)
{
var _bulkCampaign = new BulkCampaign()
{
Campaign = campaign
};
listBulkCampaign.Add(_bulkCampaign);
}
BulkServiceManager bulkServiceManager = new BulkServiceManager(_authorizationData);
string fileName = bingCampaignUpdate.csv;
var campaigns = (await bulkServiceManager.UploadEntitiesAsync(new EntityUploadParameters
{
Entities = listBulkCampaign,
OverwriteResultFile = true,
ResultFileDirectory = FileDirectory,
ResultFileName = fileName,
ResponseMode = ResponseMode.ErrorsAndResults
})).OfType<BulkCampaign>().ToList();
return new List<long?>();
}
catch (Exception ex)
{
ErrorLog.log(ex);
return new List<long?>();
}
}
You have to download .csv report and update the Campaigns.
I hope it helps you

Irony.Net allow two prefixes for variables

I try to use Irony.Net with this syntax:
!!test
!test1
where !!test - global variable
and !test1 - local variable
I wrote this code:
var local_identifier = new IdentifierTerminal("localidentifier","","!");
var global_identifier = new IdentifierTerminal("globalidentifier","","!!");
var param_identifier = new NonTerminal("paramidentifier");
param_identifier.Rule = local_identifier | global_identifier;
and I get shift-reduce error
What I am doing wrong?
With help from codeplex (https://irony.codeplex.com/discussions/546013) i solve the problem.
Result code is:
public static IdentifierTerminal CreateLocalIdentifier(string name)
{
var id = new IdentifierTerminal(name, IdOptions.None);
id.AddPrefix("!", IdOptions.IsNotKeyword);
id.StartCharCategories.AddRange(new[]
{
UnicodeCategory.UppercaseLetter, //Ul
UnicodeCategory.LowercaseLetter, //Ll
UnicodeCategory.TitlecaseLetter, //Lt
UnicodeCategory.ModifierLetter, //Lm
UnicodeCategory.OtherLetter, //Lo
UnicodeCategory.LetterNumber //Nl
});
id.CharCategories.AddRange(new[]
{
UnicodeCategory.DecimalDigitNumber, //Nd
UnicodeCategory.ConnectorPunctuation, //Pc
UnicodeCategory.SpacingCombiningMark, //Mc
UnicodeCategory.NonSpacingMark, //Mn
UnicodeCategory.Format //Cf
});
id.CharsToRemoveCategories.Add(UnicodeCategory.Format);
return id;
}
public static IdentifierTerminal CreateGlobalIdentifier(string name)
{
var id = new IdentifierTerminal(name, IdOptions.None);
id.AddPrefix("!!", IdOptions.IsNotKeyword);
id.StartCharCategories.AddRange(new[]
{
UnicodeCategory.UppercaseLetter, //Ul
UnicodeCategory.LowercaseLetter, //Ll
UnicodeCategory.TitlecaseLetter, //Lt
UnicodeCategory.ModifierLetter, //Lm
UnicodeCategory.OtherLetter, //Lo
UnicodeCategory.LetterNumber //Nl
});
id.CharCategories.AddRange(new[]
{
UnicodeCategory.DecimalDigitNumber, //Nd
UnicodeCategory.ConnectorPunctuation, //Pc
UnicodeCategory.SpacingCombiningMark, //Mc
UnicodeCategory.NonSpacingMark, //Mn
UnicodeCategory.Format //Cf
});
id.CharsToRemoveCategories.Add(UnicodeCategory.Format);
return id;
}

Google AdWords v201206 DotNet Client GetClientReport trouble

Here's what I'm doing:
Selector selector = new Selector();
selector.fields = new string[] {"CampaignId", "AdGroupId", "Id", "CriteriaType", "Criteria", "CriteriaDestinationUrl", "Clicks", "Impressions", "Cost"};
Predicate predicate = new Predicate();
predicate.field = "Status";
predicate.#operator = PredicateOperator.IN;
predicate.values = new string[] { "ACTIVE", "PAUSED" };
selector.predicates = new Predicate[] { predicate };
ReportDefinition definition = new ReportDefinition();
definition.reportName = "criteria report";
definition.reportType = ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT;
definition.downloadFormat = DownloadFormat.XML;
definition.dateRangeType = ReportDefinitionDateRangeType.YESTERDAY;
definition.selector = selector;
definition.includeZeroImpressions = true;
_handler.RunReport(new AdWordsUser(), definition);
And here's my handler method:
public void RunReport(AdWordsUser user, ReportDefinition definition)
{
if (definition != null)
{
string reportContents = string.Empty;
try
{
ReportUtilities utilities = new ReportUtilities(user);
utilities.ReportVersion = "v201206";
ClientReport report = utilities.GetClientReport(definition);
reportContents = report.Contents.ToString();
}
catch (Exception ex)
{
_errorHandler.AddError(ex);
}
}
}
Where I step through I get this error:
Report contents are invalid. - !!!2|||-1|||[ReportDefinitionError.CUSTOMER_SERVING_TYPE_REPORT_MISMATCH # selector]???
Been searching for hours trying to find a solution. Any hints?
It appears that the issue is indeed needing to pass in the customerClientID.
This document helped me picture what was going on.
I ended up modifying my code like this:
var configOptions = new Dictionary<string,string>();
configOptions.Add("clientCustomerID", customerID.ToString());
_handler.RunReport(new AdWordsUser(configOptions), definition);

Categories

Resources