Amazon MWS receiving MalformedInput on GetMyFeesEstimate - c#

I'm trying to access Amazon MWS API from my .Net application, using Products API Section Client Library - C# (https://developer.amazonservices.com/doc/products/products/v20111001/cSharp.html/138-8219342-3408216)
Everything works fine, except for GetMyFeesEstimate calls.
I use this method from example:
public GetMyFeesEstimateResponse InvokeGetMyFeesEstimate()
{
// Create a request.
GetMyFeesEstimateRequest request = new GetMyFeesEstimateRequest();
string sellerId = "example";
request.SellerId = sellerId;
string mwsAuthToken = "example";
request.MWSAuthToken = mwsAuthToken;
FeesEstimateRequestList feesEstimateRequestList = new FeesEstimateRequestList();
request.FeesEstimateRequestList = feesEstimateRequestList;
return this.client.GetMyFeesEstimate(request);
}
And I add item to FeesEstimateRequestList like this:
feesEstimateRequestList.FeesEstimateRequest.Add(new FeesEstimateRequest
{
MarketplaceId = marketplaceId,
IdType = "ASIN",
IdValue = "B0078LENZC",
PriceToEstimateFees = new PriceToEstimateFees { ListingPrice = new MoneyType { Amount = 30.49M, CurrencyCode = "GBP" }, Shipping = new MoneyType { Amount = 3.5M, CurrencyCode = "GBP" }, Points = new Points { PointsNumber = 0 } },
Identifier = "request_" + Guid.NewGuid().ToString(),
IsAmazonFulfilled = false
});
But constantly get MalformedInput error with no message describing what is wrong:
<ErrorResponse
xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<Error>
<Type>Sender</Type>
<Code>MalformedInput</Code>
</Error>
<RequestId>f79b9147-90d7-4ea2-b51c-d6c37c6a1bd0</RequestId>
</ErrorResponse>
Have someone any ideas how to make it work?

I have found solution:
Due to my OS regional settings, decimal separator in price had being set to comma, instead of dot when converting parameters to string.
I have to modify method putValue of MwsAQCall class like this:
private void putValue(object value)
{
if (value==null)
{
return;
}
if (value is IMwsObject)
{
parameterPrefix.Append('.');
(value as IMwsObject).WriteFragmentTo(this);
return;
}
string name = parameterPrefix.ToString();
if (value is DateTime)
{
parameters.Add(name, MwsUtil.GetFormattedTimestamp((DateTime)value));
return;
}
string valueStr = value.ToString();
if (value is decimal)
{
valueStr = valueStr.Replace(",", ".");
}
if (valueStr==null || valueStr.Length==0)
{
return;
}
if (value is bool)
{
valueStr = valueStr.ToLower();
}
parameters.Add(name, valueStr);
}

Related

Translate from C# to PROGRESS OPENEDGE ABL

I received an C# DLL to access an API and another C# to invoke the DLL.
I'm trying to make an ABL program to INVOKE the DLL.
Ive tried the USING, also run it as an EXTERNAL but no luck.
Never used C#, but it looks like a very simple program can't find how to instatiate the DLL from ABL.
Thanks in advance,
Hugo
Here is the C# code, will appreciate any help
Code:
using System;
using System.Windows.Forms;
namespace CayanConnectSample
{
public partial class MainFrm : Form
{
public MainFrm()
{
InitializeComponent();
}
private string merchantName = "Test Dynamic Payments";
private string merchantSiteId = "2Q5JSJH3";
private string merchantKey = "GQPXT-GTJTP-66A1Y-RWT5G-CNULU";
private string terminalIPAddress = "192.168.1.32"; //ip address in CDI Technologies
private int requestTimeout = 60;
private void btnCreateTransaction_Click(object sender, EventArgs e)
{
decimal amount = Convert.ToDecimal(0.09);
string clerkId = "MIKE";
//only transactionType used are sale & refund
CayanConnect.CreateTransaction.Request request = new CayanConnect.CreateTransaction.Request()
{
MerchantName = merchantName,
MerchantSiteId = merchantSiteId,
MerchantKey = merchantKey,
TransactionType = CayanConnect.CreateTransaction.TransactionTypeEnum.SALE,
ClerkId = clerkId,
Dba = merchantName,
Amount = amount,
//[Amount] is always positive. TransactionType has the sign. Sale or Refund
OrderNumber = "1234"
};
CayanConnect.CreateTransaction createTrx = new CayanConnect.CreateTransaction();
CayanConnect.CreateTransaction.Response ctr = createTrx.Process(request, CayanConnect.ThemeEnum.None);
if (ctr.Success)
{
CayanConnect.InitiateTransaction it = new CayanConnect.InitiateTransaction(terminalIPAddress, ctr.TransportKey, null, CayanConnect.ThemeEnum.None, "Waiting for customer...");
CayanConnect.InitiateTransaction.Response response = it.Process(requestTimeout, true);
string emvDetail = response.EMVDetail;
bool approved = false;
if (response.Success)
{
//THERE IS NO TIMEOUT OR ERROR CALLING THE SERVICE
if (response.Status.ToUpper() == "APPROVED")
{
//AN AMOUNT HAS BEEN APPROVED
if (Convert.ToDecimal(Math.Abs(amount)) == response.AmountApproved)
{
//FULL AMOUNT APPROVED
approved = true;
txtResponse.Text = "Good to go!!";
}
else
{
//PARTIALLY APPROVED, HAS TO VOID THIS
string v = this.VoidApprovedTransaction(response.Token);
string em = v.IsEmpty() ? "Transaction was voided succesfully." : v;
txtResponse.Text = $"Invalid approved amount.{Environment.NewLine}Amount: {amount.ToString("C")}{Environment.NewLine}Approved Amount: {response.AmountApproved.ToString("c")}{em}";
}
}
else
{
//AMOUNT WAS DECLINED
txtResponse.Text = response.DeclinedMessage(amount);
}
}
else
{
//THERE WAS A PROBLEM CALLING THE SERVICE
txtResponse.Text = response.ErrorMessage;
}
}
else
{
//THERE WAS A PROBLEM CALLING THE SERVICE
txtResponse.Text = ctr.ErrorMessage;
}
}
private string GetStatus()
{
string rt = string.Empty;
CayanConnect.GetStatus status = new CayanConnect.GetStatus(this.terminalIPAddress, null, CayanConnect.ThemeEnum.None, "Verifying terminal status...");
CayanConnect.GetStatus.Response statusResponse = status.Process(this.requestTimeout);
rt = statusResponse.ToXml();
return rt;
}
private string VoidApprovedTransaction(string token)
{
string rt = string.Empty;
CayanConnect.Void _void = new CayanConnect.Void();
CayanConnect.Void.Request request = new CayanConnect.Void.Request()
{
MerchantName = this.merchantName,
MerchantKey = this.merchantKey,
MerchantSiteId = this.merchantSiteId,
Token = token,
Timeout = this.requestTimeout
};
CayanConnect.Void.Response response = _void.Process(request, CayanConnect.ThemeEnum.None);
if (!response.Success)
{
rt = $"Error voiding transaction.{Environment.NewLine}{Environment.NewLine}{response.ErrorMessage}";
}
return rt;
}
private void btnIsOnLine_Click(object sender, EventArgs e)
{
txtResponse.Text = GetStatus();
}
}
}
============================================================================
You don't need to 'invoke' the DLL. I have found that the DLL's doc is very important to read - you'll need to know things like who's in charge (ABL or the DLL) of memory allocation and deallocation, structure sizes etc. Also, the AVM is not re-entrant (so cannot be registered as a callback for any DLL).
For an example of calling DLL/SO functions from within an ABL class, take a look in the repo at https://github.com/PeterJudge-PSC/abl_odbc_api .
You'll need to create function prototypes (see an example at https://github.com/PeterJudge-PSC/abl_odbc_api/blob/master/src/OpenEdge/Data/ODBC/ODBCConnectionProto.i ) and you can then call those functions from within a method . Take a look at https://github.com/PeterJudge-PSC/abl_odbc_api/blob/master/src/OpenEdge/Data/ODBC/SqlCommonFunctions.cls for examples.

Is there an override for calendar dates names or descriptions?

I'm trying to use Bloomberg API to get holiday information about a ticker, the request below produces the dates correctly but I would also like to include the name of the holiday
Could there be an override that will also include the name of the date as on "New Year"
ReferenceDataRequest = {
securities[] = {
LQ45 Index
}
fields[] = {
CALENDAR_HOLIDAYS
}
overrides[] = {
overrides = {
fieldId = "SETTLEMENT_CALENDAR_CODE"
value = "JA"
}
overrides = {
fieldId = "CALENDAR_START_DATE"
value = "20190101"
}
overrides = {
fieldId = "CALENDAR_END_DATE"
value = "20191231"
}
}
tableOverrides[] = {
}
}
the c# code I am using was suggested on another question that I can no longer find, and it is:
Request request = this._service.CreateRequest("ReferenceDataRequest");
Element securities = request.GetElement(BloombergConstants.SECURITIES);
securities.AppendValue(ticker);
Element fields = request.GetElement(BloombergConstants.FIELDS);
fields.AppendValue("CALENDAR_HOLIDAYS");
//Element overridefields = request.GetElement(BloombergConstants.OVERRIDES);
Element overrides = request.GetElement(BloombergConstants.OVERRIDES);
Element override1 = overrides.AppendElement();
override1.SetElement(BloombergConstants.FIELDID, "SETTLEMENT_CALENDAR_CODE");
override1.SetElement(BloombergConstants.VALUE, calendarCode);
override1 = overrides.AppendElement();
override1.SetElement(BloombergConstants.FIELDID , "CALENDAR_START_DATE");
override1.SetElement(BloombergConstants.VALUE, startDate.ToString("yyyyMMdd"));
Element override2 = overrides.AppendElement();
override2.SetElement(BloombergConstants.FIELDID, "CALENDAR_END_DATE");
override2.SetElement(BloombergConstants.VALUE, endDate.ToString("yyyyMMdd"));
Sadly not.
see Official Bloomberg API-Core-Developer-Guide.pdf
see Unofficial Bloomberg .Net API Implementation
Unfortunately it looks like there is no override code to add this behaviour. This is a bit non intuitive, but if you search for the relevant code CALENDAR_HOLIDAYS you actually receive information on the code CALENDAR_NON_SETTLEMENT_DATES (possibly this was renamed and aliased to this at some point?)
fieldInfoRequest = {
id[] = {
"CALENDAR_HOLIDAYS"
}
}
fieldResponse = {
fieldData[] = {
fieldData = {
id = "ZS090"
fieldInfo = {
mnemonic = "CALENDAR_NON_SETTLEMENT_DATES"
description = "Calendar Non-Settlement Dates"
datatype = String
categoryName[] = {
}
property[] = {
}
overrides[] = {
"ZS089", "ZS087", "ZS088"
}
ftype = BulkFormat
}
}
}
}
These overrides correspond to
id mnemonic
ZS087 SETTLEMENT_CALENDAR_CODE
ZS088 CALENDAR_START_DATE
ZS089 CALENDAR_END_DATE
Non of which adds functionality to return a description of the holiday the date corresponds to.

C# Authorize.net Create Profile Issue

The following code is charging the card, however it is not creating the profile....any tips? I'm assuming I'm missing something, or using the wrong Type...
var opaqueData = new opaqueDataType { dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT", dataValue = paymentNonce };
//standard api call to retrieve response
var paymentType = new paymentType { Item = opaqueData };
var transactionRequest = new transactionRequestType
{
transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), // authorize and capture transaction
amount = paymentAmount,
payment = paymentType,
customer = new customerDataType()
{
type = customerTypeEnum.individual,
id = userID.ToString()
},
profile = new customerProfilePaymentType()
{
createProfile = true
}
};
var request = new createTransactionRequest { transactionRequest = transactionRequest };
// instantiate the contoller that will call the service
var controller = new createTransactionController(request);
const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
ServicePointManager.SecurityProtocol = Tls12;
controller.Execute();
// get the response from the service (errors contained if any)
var response = controller.GetApiResponse();
UPDATE:
Since apparently OpaqueData is not allowed, I changed it to make the profile manually. I am getting the following Error: "Error: I00001 Successful."
// Add Payment method to Customer.
customerPaymentProfileType opaquePaymentProfile = new customerPaymentProfileType();
opaquePaymentProfile.payment = paymentType;
opaquePaymentProfile.customerType = customerTypeEnum.individual;
var request2 = new createCustomerPaymentProfileRequest
{
paymentProfile = opaquePaymentProfile,
validationMode = validationModeEnum.none,
customerProfileId = userID.ToString()
};
var controller2 = new createCustomerPaymentProfileController(request2);
controller2.Execute();
//Send Request to EndPoint
createCustomerPaymentProfileResponse response2 = controller2.GetApiResponse();
if (response2 != null && response2.messages.resultCode == messageTypeEnum.Ok)
{
if (response2 != null && response2.messages.message != null)
{
//Console.WriteLine("Success, createCustomerPaymentProfileID : " + response.customerPaymentProfileId);
}
}
else
{
Utility.AppendTextToFile("Error: " + response.messages.message[0].code + " " + response.messages.message[0].text, Server.MapPath("/pub/auth.txt"));
}
Update #2
Very confused as auth.net documentation says this code means success...so why don't I see the CIM payment method created??? RESPONSE CODE DOCS
Update #3
So I was printing out the main response message instead of the CIM request message, duh. The actual error was: "E00114 Invalid OTS Token."
Based on the the documentation, that error is usually from a used Key, so I am now generating 2 keys (One to process and One to store via CIM) but am now getting this error: "E00040 The record cannot be found."....Any ideas?
So the answer to this question is:
You can not auto create a payment profile using opaque card data, so the answer is to make it manually once you have a successful charge.
You can not use the same opaque card data to charge and store, as they are one time use, so for my web method I ended up passing 2 opaque data keys.
You have to make different calls for setting up a brand new customer and an existing customer just adding a new card. I have pasted an excerpt of my end solution below:
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = (System.Configuration.ConfigurationManager.AppSettings["Authorize-Live"].ToUpper() == "TRUE" ? AuthorizeNet.Environment.PRODUCTION : AuthorizeNet.Environment.SANDBOX);
// define the merchant information (authentication / transaction id)
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
{
name = (System.Configuration.ConfigurationManager.AppSettings["Authorize-Live"].ToUpper() == "TRUE" ? System.Configuration.ConfigurationManager.AppSettings["Authorize-LoginID"] : System.Configuration.ConfigurationManager.AppSettings["Authorize-LoginID-SandBox"]),
ItemElementName = ItemChoiceType.transactionKey,
Item = (System.Configuration.ConfigurationManager.AppSettings["Authorize-Live"].ToUpper() == "TRUE" ? System.Configuration.ConfigurationManager.AppSettings["Authorize-TransactionKey"] : System.Configuration.ConfigurationManager.AppSettings["Authorize-TransactionKey-SandBox"])
};
if (paymentNonce.Trim() != "")
{
//set up data based on transaction
var opaqueData = new opaqueDataType { dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT", dataValue = paymentNonce };
//standard api call to retrieve response
var paymentType = new paymentType { Item = opaqueData };
var transactionRequest = new transactionRequestType
{
transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), // authorize and capture transaction
amount = paymentAmount,
payment = paymentType,
customer = new customerDataType()
{
type = customerTypeEnum.individual,
id = "YOUR_DB_USERID"
},
profile = new customerProfilePaymentType()
{
createProfile = false
}
};
var request = new createTransactionRequest { transactionRequest = transactionRequest };
// instantiate the contoller that will call the service
var controller = new createTransactionController(request);
const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
ServicePointManager.SecurityProtocol = Tls12;
controller.Execute();
// get the response from the service (errors contained if any)
var response = controller.GetApiResponse();
//validate
if (response != null)
{
if (response.messages.resultCode == messageTypeEnum.Ok)
{
if (response.transactionResponse.messages != null)
{
responseData.Success = true;
transactionID = response.transactionResponse.transId;
string merchID = "STORED AUTHORIZE.NET CUSTOMERID, return blank string if none!";
var opaqueData2 = new opaqueDataType { dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT", dataValue = paymentNonce2 };
//standard api call to retrieve response
var paymentType2 = new paymentType { Item = opaqueData2 };
customerPaymentProfileType opaquePaymentProfile = new customerPaymentProfileType();
opaquePaymentProfile.payment = paymentType2;
opaquePaymentProfile.customerType = customerTypeEnum.individual;
if (merchID == "")
{
// CREATE NEW AUTH.NET AIM CUSTOMER
List<customerPaymentProfileType> paymentProfileList = new List<customerPaymentProfileType>();
paymentProfileList.Add(opaquePaymentProfile);
customerProfileType customerProfile = new customerProfileType();
customerProfile.merchantCustomerId = "YOUR_DB_USERID";
customerProfile.paymentProfiles = paymentProfileList.ToArray();
var cimRequest = new createCustomerProfileRequest { profile = customerProfile, validationMode = validationModeEnum.none };
var cimController = new createCustomerProfileController(cimRequest); // instantiate the contoller that will call the service
cimController.Execute();
createCustomerProfileResponse cimResponse = cimController.GetApiResponse();
if (cimResponse != null && cimResponse.messages.resultCode == messageTypeEnum.Ok)
{
if (cimResponse != null && cimResponse.messages.message != null)
{
// STORE cimResponse.customerProfileId IN DATABASE FOR USER
}
}
else
{
for (int i = 0; i < cimResponse.messages.message.Length; i++)
Utility.AppendTextToFile("New Error (" + merchID + ") #" + i.ToString() + ": " + cimResponse.messages.message[i].code + " " + cimResponse.messages.message[i].text, Server.MapPath("/pub/auth.txt"));
}
}
else
{
// ADD PAYMENT PROFILE TO EXISTING AUTH.NET AIM CUSTOMER
var cimRequest = new createCustomerPaymentProfileRequest
{
paymentProfile = opaquePaymentProfile,
validationMode = validationModeEnum.none,
customerProfileId = merchID.Trim()
};
var cimController = new createCustomerPaymentProfileController(cimRequest);
cimController.Execute();
//Send Request to EndPoint
createCustomerPaymentProfileResponse cimResponse = cimController.GetApiResponse();
if (cimResponse != null && cimResponse.messages.resultCode == messageTypeEnum.Ok)
{
if (cimResponse != null && cimResponse.messages.message != null)
{
//Console.WriteLine("Success, createCustomerPaymentProfileID : " + response.customerPaymentProfileId);
}
}
else
{
for (int i = 0; i < cimResponse.messages.message.Length; i++)
Utility.AppendTextToFile("Add Error (" + merchID + ") #" + i.ToString() + ": " + cimResponse.messages.message[i].code + " " + cimResponse.messages.message[i].text, Server.MapPath("/pub/auth.txt"));
}
}
}
else
{
responseData.Message = "Card Declined";
responseData.Success = false;
if (response.transactionResponse.errors != null)
{
responseData.Message = response.transactionResponse.errors[0].errorText;
}
}
}
else
{
responseData.Message = "Failed Transaction";
responseData.Success = false;
if (response.transactionResponse != null && response.transactionResponse.errors != null)
{
responseData.Message = response.transactionResponse.errors[0].errorText;
}
else
{
responseData.Message = response.messages.message[0].text;
}
}
}
else
{
responseData.Message = "Failed Transaction, Try Again!";
responseData.Success = false;
}
}
else
{
// RUN PAYMENT WITH STORED PAYMENT PROFILE ID
customerProfilePaymentType profileToCharge = new customerProfilePaymentType();
profileToCharge.customerProfileId = CustomerID;
profileToCharge.paymentProfile = new paymentProfile { paymentProfileId = PaymentID };
var transactionRequest = new transactionRequestType
{
transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),
amount = paymentAmount,
profile = profileToCharge
};
var request = new createTransactionRequest { transactionRequest = transactionRequest };
// instantiate the collector that will call the service
var controller = new createTransactionController(request);
controller.Execute();
// get the response from the service (errors contained if any)
var response = controller.GetApiResponse();
//validate
if (response != null)
{
if (response.messages.resultCode == messageTypeEnum.Ok)
{
if (response.transactionResponse.messages != null)
{
responseData.Success = true;
transactionID = response.transactionResponse.transId;
}
else
{
responseData.Message = "Card Declined";
responseData.Success = false;
if (response.transactionResponse.errors != null)
{
responseData.Message = response.transactionResponse.errors[0].errorText;
}
}
}
else
{
responseData.Message = "Failed Transaction";
responseData.Success = false;
if (response.transactionResponse != null && response.transactionResponse.errors != null)
{
responseData.Message = response.transactionResponse.errors[0].errorText;
}
else
{
responseData.Message = response.messages.message[0].text;
}
}
}
else
{
responseData.Message = "Failed Transaction, Try Again!";
responseData.Success = false;
}
}

Sony Camera API with C#

I have asked a previous question on SO with regards to the Sony Camera API and I did get some help but I am still having a problem. I found the following library https://github.com/kazyx/kz-remote-api that someone made to use with the Sony Camera API but I had to make changes to it to work with a WPF app as it was optimized for windows store apps.
I am now resorting to do everything myself but I am unsure if I need to attach a Camera API file to my solution and if I do where can I find the exact file because the one the API file that I downloaded only has files for Android and iOS in which won't help me.
I finally got my thing working and I tried to put it in such a manner so that it is easily understandable. If anyone would like my Sony Library that I wrote that please let me know as I also tried the Kazyx library and that didn't work for me.
My code is below.
private string cameraURL;
private bool recModeActive;
public void ControlCamera(string cameraResp)
{
cameraURL = string.Format("{0}/{1}", GetCameraURL(cameraResp), GetActionType(cameraResp));
}
private string CameraRequest(string cameraUrl, string cameraRequest)
{
Uri urlURI = new Uri(cameraURL);
HttpWebRequest cameraReq = (HttpWebRequest)WebRequest.Create(cameraURL);
cameraReq.Method = "POST";
cameraReq.AllowWriteStreamBuffering = false;
cameraReq.ContentType = "application/json; charset=utf-8";
cameraReq.Accept = "Accept-application/json";
cameraReq.ContentLength = cameraRequest.Length;
using (var cameraWrite = new StreamWriter(cameraReq.GetRequestStream()))
{
cameraWrite.Write(cameraRequest);
}
var cameraResp = (HttpWebResponse)cameraReq.GetResponse();
Stream cameraStream = cameraResp.GetResponseStream();
StreamReader cameraRead = new StreamReader(cameraStream);
string readCamera = cameraRead.ReadToEnd();
return readCamera;
}
public string GetCameraURL(string cameraResp)
{
string[] cameraXML = cameraResp.Split('\n');
string cameraURL = "";
foreach (string cameraString in cameraXML)
{
string getCameraURL = "";
if (cameraString.Contains("<av:X_ScalarWebAPI_ActionList_URL>"))
{
getCameraURL = cameraString.Substring(cameraString.IndexOf('>') + 1);
cameraURL = getCameraURL.Substring(0, getCameraURL.IndexOf('<'));
}
}
return cameraURL;
}
public string GetActionType(string cameraResp)
{
string[] cameraXML = cameraResp.Split('\n');
string actionType = "";
foreach (string cameraString in cameraXML)
{
string getType = "";
if (cameraString.Contains("<av:X_ScalarWebAPI_ServiceType>"))
{
getType = cameraString.Substring(cameraString.IndexOf('>') + 1);
actionType = getType.Substring(0, getType.IndexOf('<'));
if (actionType == "camera")
{
break;
}
}
}
return actionType;
}
public string StartRecMode()
{
string startRecMode = JsonConvert.SerializeObject(new Camera.CameraSetup
{
method = "startRecMode",
#params = new List<string> { },
id = 1,
version = "1.0"
});
recModeActive = true;
return CameraRequest(cameraURL, startRecMode);
}
public string TriggerCamera()
{
string _triggerCamera = JsonConvert.SerializeObject(new Camera.StillCapture
{
method = "actTakePicture",
#params = new List<string> { },
id = 1,
version = "1.0"
});
return CameraRequest(cameraURL, _triggerCamera);
}
public string EchoRequest()
{
string _echoRequest = JsonConvert.SerializeObject(new Camera.TestCameraComm
{
method = "getEvent",
#params = new List<bool> { true },
id = 1,
version = "1.0"
});
return CameraRequest(cameraURL, _echoRequest);
}
public string StopRecMode()
{
string stopRecMode = JsonConvert.SerializeObject(new Camera.CameraSetup
{
method = "stopRecMode",
#params = new List<string> { },
id = 1,
version = "1.0"
});
recModeActive = false;
return CameraRequest(cameraURL, stopRecMode);
}
public string SetImageQuality()
{
string qualityReq = JsonConvert.SerializeObject(new Camera.CameraSetup
{
method = "setStillSize",
#params = new List<string> { "4:3", "20M"},
id = 1,
version = "1.0"
});
recModeActive = false;
return CameraRequest(cameraURL, qualityReq);
}`

asp.net mvc 4 accessing websecurity.Getuserid(user.identity.name)

I am trying to access to the user id that is currently logged on...
I have two controllers, LicencaController and ProcessoController.
In the ProcessoController there is a function that saves the user id and some other stuff,
this function was private, but in order to gain access I have change it to public..
Now in a function in the controller Licenca I instaciate an object ProcessoController and called the function on the ProcessoController...
The problem is that user.identity.name is null.
If from the ProcessoController I call the function to save the user id , user.identity.name gives me the username...
If from the LicencaController I call the function to save the user id that is declared in the ProcessoController, it gives me null...
I have tried other solutions like the one in this topic:
Authentication issue when debugging in VS2013 - iis express
but it's not working...
Is it possible to do this?
What is the problem?
Thanks in advance...
Here goes the code:
Fucntion SaveProcessoSoftware in the controller ProcessoProduto
public string SaveProcessoSoftware(int iIDProcesso, int iIDSoftware, int iIDTipoLicenciamento,
List<string> NomeVariaveis, List<string> ValorVariaveis, string sNrFactura, string sIDLicencaInicial, string sDescricaoTipoSoftware)
{
int iIDFactura = GetIDFactura(sNrFactura);
string sIDLicenca = SetLicenca(iIDSoftware, sIDLicencaInicial, sDescricaoTipoSoftware);
ProcessoProdutos objProcSoft = new ProcessoProdutos();
objProcSoft.IDProcesso = iIDProcesso;
objProcSoft.IDLicencaSoftware = sIDLicenca;
objProcSoft.IDFactura = iIDFactura;
objProcSoft.Rem = 0;
objProcSoft.IDU = WebSecurity.CurrentUserId;// .GetUserId(User.Identity.Name);
objProcSoft.TStamp = GetDateTimeFromSqlSytem();
db.ProcessoProdutos.Add(objProcSoft);
db.SaveChanges();
if (NomeVariaveis != null)
SaveVariaveis(sIDLicenca, iIDTipoLicenciamento, NomeVariaveis, ValorVariaveis);
return sIDLicenca;
}
Function SetLicenca...this is function where i save the user id...
public string SetLicenca(int iIDSoftware, string sIDLicenca, string sDescricaoTipoSoftware)
{
string LastTableIDLicenca = "";
Licenca Lic = new Licenca();
Lic.IDProduto = iIDSoftware;
Lic.Estado = 4;
Lic.Observacoes = "";
Lic.DataValidade = DateTime.MaxValue;
Lic.Validado = 2;
Lic.IDValidado = 0;
Lic.IDTitular = 0;
Lic.Rem = 0;
Lic.IDU = WebSecurity.GetUserId(User.Identity.Name);<---error
Lic.TStamp = GetDateTimeFromSqlSytem();
Lic.IDLicenca = new Licenciamento_v2.Areas.Idonic.IDLicencaGenerator().GenerateCharID(8);
db.Licencas.Add(Lic);
int t = SaveLicenca();
if (t == -1)
SetLicenca(iIDSoftware, sIDLicenca, sDescricaoTipoSoftware);
else
{
LastTableIDLicenca = Lic.IDLicenca;
//obter o id introduzido e actualizar o campo idInicial
if (sDescricaoTipoSoftware.Equals("Software") == true)
{
Lic = db.Licencas.Find(LastTableIDLicenca);
if (sIDLicenca != "")
{
Licenca LicAnt = db.Licencas.Find(sIDLicenca);
Lic.IDInicial = LicAnt.IDInicial;
}
else
{
Lic.IDInicial = LastTableIDLicenca;
}
db.SaveChanges();
}
}
return LastTableIDLicenca;
}
From LicencaController i do this:
public void SaveSoftwareToLicenca()
{
int sessionIDProcesso = (int)Session["EditIDProcesso"];
ProcessoController procCont = new ProcessoController();
procCont.ChangeProcessoProdutoStatus(sessionIDProcesso, t.rowId, 1);
procCont.ChangeLicencaEstado(t.rowId, 3);
procCont.ChangeLicencaVariaveisStatus(t.rowId, 1);
Session["IDLicenca"] = procCont.SaveProcessoSoftware(sessionIDProcesso, t.row.IDSoftware, t.row.IDNivelDeLicenciamento, t.row.NomeVariaveis, t.row.ValorVariaveis, t.row.NumeroFactura, t.row.IDLicenca, t.row.DescricaoTipoDeSoftware);
}
Thanks again for the help..

Categories

Resources