C# Authorize.net Create Profile Issue - c#

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;
}
}

Related

Blank values received when using RestSharp from Console Application

I've created a C# console application that calls a stored procedure from SQL Server, retrieves records from a database table where records have not been transmitted, and adds said records to a RestSharp request. When I run my application locally, OK Status is received with a Status Code reflecting missing information. The API's logging system shows empty values in the received request.
I've tried the RestSharp request as follows:
private static RestRequest CreateRestRequest(string resource, Method method)
{
var credentials = GetCredentials();
var restRequest = new RestRequest { Resource = resource, Method = method, RequestFormat = DataFormat.Json, };
restRequest.AddHeader("accept", "application/json");
restRequest.AddHeader("Authorization", credentials);
restRequest.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
restRequest.OnBeforeDeserialization = resp => { resp.ContentEncoding = "utf-8"; };
restRequest.OnBeforeDeserialization = resp =>
{
if (resp.RawBytes.Length >= 3 && resp.RawBytes[0] == 0xEF && resp.RawBytes[1] == 0xBB && resp.RawBytes[2] == 0xBF)
{
// Copy the data but with the UTF-8 BOM removed.
var newData = new byte[resp.RawBytes.Length - 3];
Buffer.BlockCopy(resp.RawBytes, 3, newData, 0, newData.Length);
resp.RawBytes = newData;
// Force re-conversion to string on next access
resp.Content = null;
}
};
Console.WriteLine(restRequest);
return restRequest;
}
The logic used for the request values is as follows:
private SignUpRequest BuildMerchantTestData()
{
var onboardingDAL = new OnboardingDAL(iconfiguration);
var onboardingList = onboardingDAL.GetOnboardingList(iconfiguration);
var ownerList = new List<OwnerList>();
if (onboardingList != null)
{
Debug.Assert(onboardingList != null, nameof(OnboardingList) + " != null");
foreach (Onboarding result in onboardingList)
{
Console.WriteLine("{0} {1}", result.Email, result.UserId);
List<Owner> owner1 = new List<Owner>{ new Owner
{
FirstName = result.OwnerFirstName,
LastName = result.OwnerLastName,
Address = result.OwnerAddress,
City = result.OwnerCity,
State = result.OwnerRegion,
Zip = result.OwnerZipCode,
Country =result.OwnerCountry,
DateOfBirth = result.OwnerDob,
SSN = result.OwnerSsn,
Email = result.Email,
Percentage = result.OwnerPercentage,
Title = result.OwnerTitle
}};
var signupRequest = new SignUpRequest
{
PersonalData = new PersonalData
{
FirstName = result.FirstName,
MiddleInitial = result.MiddleInitial,
LastName = result.Lastname,
DateOfBirth = result.DateOfBirth,
SocialSecurityNumber = result.Ssn,
SourceEmail = result.Email,
PhoneInformation =
new PhoneInformation
{DayPhone = result.DayPhone, EveningPhone = result.EveningPhone},
},
InternationalSignUpData = null,
NotificationEmail = result.Email,
SignupAccountData = new SignupAccountData
{
CurrencyCode = "USD",
Tier = "Test"
},
BusinessData =
new BusinessData
{
BusinessLegalName = result.BusinessLegalName,
DoingBusinessAs = result.DoingBusinessAs,
EIN = result.Ein,
MerchantCategoryCode = result.MerchantCategoryCode,
WebsiteURL = result.BusinessUrl,
BusinessDescription = result.BusinessDescription,
MonthlyBankCardVolume = result.MonthlyBankCardVolume ?? 0,
AverageTicket = result.AverageTicket ?? 0,
HighestTicket = result.HighestTicket ?? 0
},
Address = new Address
{
ApartmentNumber = result.Address1ApartmentNumber,
Address1 = result.Address1Line1,
Address2 = result.Address1Line1,
City = result.Address1City,
State = result.Address1State,
Country = result.Address1Country,
Zip = result.Address1ZipCode
},
MailAddress = new Address
{
ApartmentNumber = result.OwnerApartmentNumber,
Address1 = result.OwnerAddress,
Address2 = result.OwnerAddress2,
City = result.OwnerCity,
State = result.OwnerRegion,
Country = result.OwnerCountry,
Zip = result.OwnerZipCode
},
BusinessAddress =
new Address
{
ApartmentNumber = result.BusinessApartmentNumber,
Address1 = result.BusinessAddressLine1,
Address2 = result.BusinessAddressLine2,
City = result.BusinessCity,
State = result.BusinessState,
Country = result.BusinessCountry,
Zip = result.BusinessZipCode
},
BankAccount =
new BankAccount
{
AccountCountryCode = result.BankAccount1CountryCode,
BankAccountNumber = result.BankAccount1Number,
RoutingNumber = result.BankAccount1RoutingNumber,
AccountOwnershipType = result.BankAccount1OwnershipType,
BankName = result.BankAccount1BankName,
AccountType = "Checking",
AccountName = result.BankAccount1Name,
Description = result.BankAccount1Description
},
BeneficialOwnerData = new BeneficialOwnerData
{
OwnerCount = "1",
Owners = owner1
}
}; Console.WriteLine(JsonConvert.SerializeObject(signupRequest));
}
}
return new SignUpRequest();
}
I'm executing the request as follows:
private static T Execute<T>(IRestRequest request, string baseUrl) where T : class, new()
{
var client = new RestClient(baseUrl);
var response = client.Execute<T>(request);
if (response.ErrorException != null)
{
Console.WriteLine(
"Error: Exception: {0}, Message: {1}, Headers: {2}, Content: {3}, Status Code: {4}",
response.ErrorException,
response.ErrorMessage,
response.Headers,
response.Content,
response.StatusCode);
}
Console.WriteLine("Status:" + response.StatusCode);
Console.WriteLine("Message: " + response.Content);
Console.WriteLine(response.Data);
return response.Data;
}
public ProPayResponse MerchantSignUpForProPay()
{
var baseUrl = "https://xmltestapi.propay.com/ProPayAPI";
var request = BuildMerchantTestData();
var restRequest = CreateRestRequest("SignUp", Method.PUT);
restRequest.AddJsonBody(request);
_context?.SaveChangesAsync();
return Execute<ProPayResponse>(restRequest, baseUrl);
}
Why would the JSON string contain valid values in my console, but yet no values are received by the API? How would I rectify this issue?
So, after re-visiting this issue at a later time, I found that return signupRequest; was the appropriate way to return the request and request values.

Async function in Converting object to another object in c#

I would like to implement an async function in converting the object to another object then in saving to the database.
public List<Order> GetOrdersFromTradeGeckoCount()
{
string orderLimit = base.StorePlugin.Store.OrderLimit.HasValue ? base.StorePlugin.Store.OrderLimit.Value.ToString() : "250";
string filters = string.Format("?status=finalized&limit={0}", orderLimit);
HttpResponseMessage response = _requestHelper.GetHttpResponse("orders" + filters);
var tgOrders = GetOrdersResponse(response);
//Async Convert and Save Order
ConvertToORouterOrdersAsync(tgOrders);
return ConvertToORouterOrdersCount(tgOrders);
}
I would like this method ConvertToORouterOrdersAsync(tgOrders); will run in the background and will return the Count of Orders from this ConvertToORouterOrdersCount(tgOrders) before the conversion is done.
Please help me to change the implementation to asynchronous.
public async void ConvertToORouterOrdersAsync(List<TGOrder> tgOrders)
{
var orderMgr = new OrderDAC();
var orders = new List<Order>(tgOrders.Count());
foreach (TGOrder tgOrder in tgOrders)
{
try
{
var order = new Order();
var orderId = TryConvertInt64(CleanUpOrderId(tgOrder.order_number));
if (orderId == null) continue;
var tempOrderId = string.Format("{0}{1}", base.StoreId, orderId.Value);
order.OrderId = TryConvertInt64(tempOrderId).Value;
order.StoreOrderId = tgOrder.id.ToString();
order.WarehouseOrderId = tgOrder.order_number;
var orderFromDb = orderMgr.GetOrder(order.OrderId, base.StoreId);
if (orderFromDb != null) continue; // make sure we only import new order(i.e. doesn't exists in database)
// shipping address
var tgShippingAddress = GetAddress(tgOrder.shipping_address_id);
if (tgShippingAddress == null) continue;
order.ShipFirstName = tgShippingAddress.first_name;
order.ShipLastName = tgShippingAddress.last_name;
order.ShipCompanyName = tgShippingAddress.company_name;
order.ShipAddress1 = tgShippingAddress.address1;
order.ShipAddress2 = tgShippingAddress.address2;
order.ShipCity = tgShippingAddress.suburb;
order.ShipState = tgShippingAddress.state;
order.ShipPostalCode = tgShippingAddress.zip_code;
order.ShipCountry = tgShippingAddress.country;
order.ShipPhoneNumber = tgShippingAddress.phone_number;
order.CustomerEmail = tgOrder.email;
// billing address
var tgBillingAddress = GetAddress(tgOrder.billing_address_id);
if (tgBillingAddress == null) continue;
// line items
var lineItems = GetOrderLineItems(tgOrder.id);
foreach (TGOrderLineItem lineItem in lineItems)
{
var ol = new OrderLine();
if (lineItem.variant_id.HasValue)
{
var variant = GetVariant(lineItem.variant_id.Value);
if (variant == null) continue;
ol.ProductName = variant.product_name;
ol.SKU = variant.sku;
ol.ThreePLSKU = ol.SKU;
ol.Qty = Convert.ToInt16(TryGetDecimal(lineItem.quantity));
ol.OrderId = order.OrderId;
ol.Price = TryGetDecimal(lineItem.price);
ol.SubTotal = (ol.Qty * ol.Price);
ol.StoreOrderLineId = Convert.ToString(lineItem.id);
order.OrderLines.Add(ol);
}
}
var validator = new Validator(base.Task);
if (validator.IsValidOrder(order))
{
orderMgr.Add(order);
}
}
catch (Exception ex)
{
AppendError(ex.Message);
}
}
}
To really have a advantage of the async and await the underlying calls should have async versions, for example the database calls should be async, don't know if you use EF or just plain SqlCommand but both have async versions of their calls.
Other calls that can be async is HTTP calls.
I have edited youre code with the assumption you are able to convert the underlying code to async.
public async Task<List<Order> GetOrdersFromTradeGeckoCount()
{
string orderLimit = base.StorePlugin.Store.OrderLimit.HasValue ? base.StorePlugin.Store.OrderLimit.Value.ToString() : "250";
string filters = string.Format("?status=finalized&limit={0}", orderLimit);
HttpResponseMessage response = await _requestHelper.GetHttpResponseAsync("orders" + filters).ConfigureAwait(false);
var tgOrders = GetOrdersResponse(response);
//Async Convert and Save Order
await ConvertToORouterOrdersAsync(tgOrders).ConfigureAwait(false);
return await ConvertToORouterOrdersCountAsync(tgOrders).ConfigureAwait(false);
}
public async Task ConvertToORouterOrdersAsync(List<TGOrder> tgOrders)
{
var orderMgr = new OrderDAC();
var orders = new List<Order>(tgOrders.Count());
foreach (TGOrder tgOrder in tgOrders)
{
try
{
var order = new Order();
var orderId = TryConvertInt64(CleanUpOrderId(tgOrder.order_number));
if (orderId == null) continue;
var tempOrderId = string.Format("{0}{1}", base.StoreId, orderId.Value);
order.OrderId = TryConvertInt64(tempOrderId).Value;
order.StoreOrderId = tgOrder.id.ToString();
order.WarehouseOrderId = tgOrder.order_number;
var orderFromDb = await orderMgr.GetOrderAsync(order.OrderId, base.StoreId).ConfigureAwait(false);
if (orderFromDb != null) continue; // make sure we only import new order(i.e. doesn't exists in database)
// shipping address
var tgShippingAddress = GetAddress(tgOrder.shipping_address_id);
if (tgShippingAddress == null) continue;
order.ShipFirstName = tgShippingAddress.first_name;
order.ShipLastName = tgShippingAddress.last_name;
order.ShipCompanyName = tgShippingAddress.company_name;
order.ShipAddress1 = tgShippingAddress.address1;
order.ShipAddress2 = tgShippingAddress.address2;
order.ShipCity = tgShippingAddress.suburb;
order.ShipState = tgShippingAddress.state;
order.ShipPostalCode = tgShippingAddress.zip_code;
order.ShipCountry = tgShippingAddress.country;
order.ShipPhoneNumber = tgShippingAddress.phone_number;
order.CustomerEmail = tgOrder.email;
// billing address
var tgBillingAddress = GetAddress(tgOrder.billing_address_id);
if (tgBillingAddress == null) continue;
// line items
var lineItems = GetOrderLineItems(tgOrder.id);
foreach (TGOrderLineItem lineItem in lineItems)
{
var ol = new OrderLine();
if (lineItem.variant_id.HasValue)
{
var variant = GetVariant(lineItem.variant_id.Value);
if (variant == null) continue;
ol.ProductName = variant.product_name;
ol.SKU = variant.sku;
ol.ThreePLSKU = ol.SKU;
ol.Qty = Convert.ToInt16(TryGetDecimal(lineItem.quantity));
ol.OrderId = order.OrderId;
ol.Price = TryGetDecimal(lineItem.price);
ol.SubTotal = (ol.Qty * ol.Price);
ol.StoreOrderLineId = Convert.ToString(lineItem.id);
order.OrderLines.Add(ol);
}
}
var validator = new Validator(base.Task);
if (validator.IsValidOrder(order))
{
await orderMgr.AddAsync(order).ConfigureAwait(false);
}
}
catch (Exception ex)
{
AppendError(ex.Message);
}
}
}
Or if you just want to run the code in the background you can also just wrap it in a Task.Run
public async Task<List<Order> GetOrdersFromTradeGeckoCount()
{
string orderLimit = base.StorePlugin.Store.OrderLimit.HasValue ? base.StorePlugin.Store.OrderLimit.Value.ToString() : "250";
string filters = string.Format("?status=finalized&limit={0}", orderLimit);
HttpResponseMessage response = _requestHelper.GetHttpResponse("orders" + filters);
var tgOrders = GetOrdersResponse(response);
//Async Convert and Save Order
await ConvertToORouterOrdersAsync(tgOrders).ConfigureAwait(false);
return ConvertToORouterOrdersCount(tgOrders);
}
public Task ConvertToORouterOrdersAsync(List<TGOrder> tgOrders)
{
return Task.Run(() =>
{
var orderMgr = new OrderDAC();
var orders = new List<Order>(tgOrders.Count());
foreach (TGOrder tgOrder in tgOrders)
{
try
{
var order = new Order();
var orderId = TryConvertInt64(CleanUpOrderId(tgOrder.order_number));
if (orderId == null) continue;
var tempOrderId = string.Format("{0}{1}", base.StoreId, orderId.Value);
order.OrderId = TryConvertInt64(tempOrderId).Value;
order.StoreOrderId = tgOrder.id.ToString();
order.WarehouseOrderId = tgOrder.order_number;
var orderFromDb = await orderMgr.GetOrder(order.OrderId, base.StoreId);
if (orderFromDb != null) continue; // make sure we only import new order(i.e. doesn't exists in database)
// shipping address
var tgShippingAddress = GetAddress(tgOrder.shipping_address_id);
if (tgShippingAddress == null) continue;
order.ShipFirstName = tgShippingAddress.first_name;
order.ShipLastName = tgShippingAddress.last_name;
order.ShipCompanyName = tgShippingAddress.company_name;
order.ShipAddress1 = tgShippingAddress.address1;
order.ShipAddress2 = tgShippingAddress.address2;
order.ShipCity = tgShippingAddress.suburb;
order.ShipState = tgShippingAddress.state;
order.ShipPostalCode = tgShippingAddress.zip_code;
order.ShipCountry = tgShippingAddress.country;
order.ShipPhoneNumber = tgShippingAddress.phone_number;
order.CustomerEmail = tgOrder.email;
// billing address
var tgBillingAddress = GetAddress(tgOrder.billing_address_id);
if (tgBillingAddress == null) continue;
// line items
var lineItems = GetOrderLineItems(tgOrder.id);
foreach (TGOrderLineItem lineItem in lineItems)
{
var ol = new OrderLine();
if (lineItem.variant_id.HasValue)
{
var variant = GetVariant(lineItem.variant_id.Value);
if (variant == null) continue;
ol.ProductName = variant.product_name;
ol.SKU = variant.sku;
ol.ThreePLSKU = ol.SKU;
ol.Qty = Convert.ToInt16(TryGetDecimal(lineItem.quantity));
ol.OrderId = order.OrderId;
ol.Price = TryGetDecimal(lineItem.price);
ol.SubTotal = (ol.Qty * ol.Price);
ol.StoreOrderLineId = Convert.ToString(lineItem.id);
order.OrderLines.Add(ol);
}
}
var validator = new Validator(base.Task);
if (validator.IsValidOrder(order))
{
orderMgr.Add(order);
}
}
catch (Exception ex)
{
AppendError(ex.Message);
}
}
});
}

Controller is returning blank View in my website

public async Task<IActionResult> Contact1()
{
if (Convert.ToBoolean(HttpContext.Session.GetString("login")))
{
var pass = new ContactViewModel();
var username = HttpContext.Session.GetString("username");
Program.readname(HttpContext.Session.GetString("username"));
var names = HttpContext.Session.GetString("studentnames");
var obj1 = JsonConvert.DeserializeObject<Program.Data>(names);
if (Program.datecheck(username, DateTime.Today.Date))
{
try{
var handler = new HttpClientHandler { Credentials = new NetworkCredential(user, password) };
using (var client = Program.CreateHttpClient(handler, user, database3))
{
string check = username + Convert.ToString(DateTime.Today.Date);
var readresponse = client.GetStringAsync(check).Result;
var obj2 = JsonConvert.DeserializeObject<Program.Data>(readresponse);
}
catch(Exception ee)
{ ViewBag.m6 = ee.Message; ViewBag.attendance = "Attendace is not take yet";}
}
pass.studentattend = obj2.studentattend1;
}
}
else { ViewBag.attendance = "Attendace is not take yet"; }
pass.studentname = obj1.studentname1;
pass.studentrollno = obj1.studentrollno1;
pass.date = DateTime.Today.Date;
HttpContext.Session.SetInt32("classselect", 1);
ViewData["Message"] = "Student Attendance of Class: " + HttpContext.Session.GetString("classname1");
ViewBag.Login = HttpContext.Session.GetString("login");
ViewBag.name = HttpContext.Session.GetString("name");
ViewBag.classname1 = HttpContext.Session.GetString("classname1");
ViewBag.classname2 = HttpContext.Session.GetString("classname2");
ViewBag.classname3 = HttpContext.Session.GetString("classname3");
ViewBag.classname4 = HttpContext.Session.GetString("classname4");
return View("/Views/Home/Contact.cshtml", pass);
}
else
{
ViewData["Message"] = "Please Login First!!";
return View("/Views/Home/Login.cshtml");
}
}
The above code is runnig well in my local ISS server but when i run this on bluemix then i am getting blank page. I tried to find out the problem and get to the conclusion that if the control does not enter in the if part of that code:
if (Program.datecheck(username, DateTime.Today.Date))
{
var handler = new HttpClientHandler { Credentials = new NetworkCredential(user, password) };
using (var client = Program.CreateHttpClient(handler, user, database3))
{
string check = username + Convert.ToString(DateTime.Today.Date);
var readresponse = client.GetStringAsync(check).Result;
var obj2 = JsonConvert.DeserializeObject<Program.Data>(readresponse);
pass.studentattend = obj2.studentattend1;
}
}
else { ViewBag.attendance = "Attendace is not take yet"; }
then it will run fine.I am unable to find what is wrong in that query.

Royal Mail Shipping API C#

I'm trying to integrate the Royal Mail SOAP API into my .NET Code. I have followed the advice here Consume WCF Royal Mail API in c# Console Application and here C# WCF Namespaces Move To Header & Use NS Prefix.
I have created a custom IClientMessageFormatter to be able to attach the namespaces to the beginning of the soap envelope, but I still can't seem to get this to work. I keep receiving the following error. Could not establish trust relationship for the SSL/TLS secure channel with authority 'api.royalmail.com', and the inner exception is: The remote certificate is invalid according to the validation procedure.
I am using Visual Studio 13 and .Net version 3.5, I've tried numerous other versions but with no further progress. When I debug I can see that the normal message been passed into the RoyalMailMessage but when it runs OnWriteStartEnvelope I can't see any changes to the _message object. I've created a trace to see what soap request is been sent.
I have sent my XML request to Royal Mail support who validate that the reason it is failing is due to the namespaces not been declared in the envelope and the missing prefixes.
RoyalMail.cs
internal class RoyalMail
{
private readonly X509Certificate2 _certificate;
private readonly Config _config;
public RoyalMail()
{
_config = new Config();
_config.LoadConfig();
// Load The SSL Certificate (Check The File Exists)
var certificatePath = (Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + #"\" + _config.GetCertificateName());
if (!File.Exists(certificatePath))
{
throw new Exception(#"The Royal Mail Certificate Is Missing From The Plugins Directory. Please Place The File " + _config.GetCertificateName() + " In The Same Directory As The Plugin DLL File & Relaunch FileMaker.\n\n" + certificatePath);
}
_certificate = new X509Certificate2(certificatePath, _config.GetCertificatePassword());
// Check It's In The Certificate
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
if (!store.Certificates.Contains(_certificate))
{
store.Add(_certificate);
MessageBox.Show("Certificate Was Installed Into Computer Trust Store");
}
store.Close();
}
/*
*
* SOAP Service & Methods
*
*/
private shippingAPIPortTypeClient GetProxy()
{
var myBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport)
{
MaxReceivedMessageSize = 2147483647
};
myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
var uri = new Uri(_config.GetEndpointUrl());
var endpointIdentity = EndpointIdentity.CreateDnsIdentity("api.royalmail.com");
var shippingClient = new shippingAPIPortTypeClient(myBinding, new EndpointAddress(uri, endpointIdentity, new AddressHeaderCollection()));
if (shippingClient.ClientCredentials != null)
shippingClient.ClientCredentials.ClientCertificate.Certificate = _certificate;
foreach (var od in shippingClient.Endpoint.Contract.Operations)
{
od.Behaviors.Add(new RoyalMailIEndpointBehavior());
}
return shippingClient;
}
private SecurityHeaderType GetSecurityHeaderType()
{
var securityHeader = new SecurityHeaderType();
var creationDate = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
var nonce = (new Random().Next(0, int.MaxValue)).ToString();
var hashedPassword = GetSha1(_config.GetPassword());
var concatednatedDigestInput = string.Concat(nonce, creationDate, Encoding.Default.GetString(hashedPassword));
var digest = GetSha1(concatednatedDigestInput);
var passwordDigest = Convert.ToBase64String(digest);
var encodedNonce = Convert.ToBase64String(Encoding.Default.GetBytes(nonce));
var doc = new XmlDocument();
using (var writer = doc.CreateNavigator().AppendChild())
{
writer.WriteStartDocument();
writer.WriteStartElement("wsse", "Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
writer.WriteStartElement("wsse", "UsernameToken", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
writer.WriteElementString("wsse", "Username", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", _config.GetUsername());
writer.WriteElementString("wsse", "Password", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", passwordDigest);
writer.WriteElementString("wsse", "Nonce", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", encodedNonce);
writer.WriteElementString("wsse", "Created", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", creationDate);
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
}
if (doc.DocumentElement != null)
{
doc.DocumentElement.RemoveAllAttributes();
var headers = doc.DocumentElement.ChildNodes.Cast<XmlElement>().ToArray();
securityHeader.Any = headers;
}
return securityHeader;
}
private integrationHeader GetIntegrationHeader()
{
var header = new integrationHeader();
var created = DateTime.Now;
var createdAt = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
header.dateTime = created;
header.version = int.Parse(_config.GetVersion());
header.dateTimeSpecified = true;
header.versionSpecified = true;
var idStructure = new identificationStructure {applicationId = _config.GetApplicationId()};
var nonce = new Random().Next(0, int.MaxValue).ToString();
idStructure.transactionId = CalculateMd5Hash(nonce + createdAt);
header.identification = idStructure;
return header;
}
private static byte[] GetSha1(string input)
{
return SHA1Managed.Create().ComputeHash(Encoding.Default.GetBytes(input));
}
public string CalculateMd5Hash(string input)
{
// step 1, calculate MD5 hash from input
var md5 = MD5.Create();
var inputBytes = Encoding.ASCII.GetBytes(input);
var hash = md5.ComputeHash(inputBytes);
// step 2, convert byte array to hex string
var sb = new StringBuilder();
foreach (var t in hash)
{
sb.Append(t.ToString("X2"));
}
return sb.ToString();
}
/*
* Check Response Footer For Errors & Warnings From Service
* If Error Return True So We Can Inform File maker Of Error
* Ignore Warnings For Now
*
*/
private static void CheckErrorsAndWarnings(integrationFooter integrationFooter)
{
if (integrationFooter != null)
{
if (integrationFooter.errors != null && integrationFooter.errors.Length > 0)
{
var errors = integrationFooter.errors;
foreach (var error in errors)
{
MessageBox.Show("Royal Mail Request Error: " + error.errorDescription + ". " + error.errorResolution, "Royal Mail Request Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
}
if (errors.Length > 0)
{
return;
}
}
if (integrationFooter.warnings != null && integrationFooter.warnings.Length > 0)
{
var warnings = integrationFooter.warnings;
foreach (var warning in warnings)
{
MessageBox.Show("Royal Mail Request Warning: " + warning.warningDescription + ". " + warning.warningResolution, "Royal Mail Request Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
}
}
}
}
/*
* Show Message Box With SOAP Error If We Receive A Fault Code Back From Service
*
*/
private static void ShowSoapException(FaultException e)
{
var message = e.CreateMessageFault();
var errorDetail = message.GetDetail<XmlElement>();
var errorDetails = errorDetail.ChildNodes;
var fullErrorDetails = "";
for (var i = 0; i < errorDetails.Count; i++)
{
var xmlNode = errorDetails.Item(i);
if (xmlNode != null)
fullErrorDetails += xmlNode.Name + ": " + xmlNode.InnerText + "\n";
}
MessageBox.Show("An Error Occured With Royal Mail Service: " + message.Reason + "\n\n" + fullErrorDetails, "Royal Mail SOAP Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
}
public createShipmentResponse SendCreateShipmentRequest(CreateShipmentForm shippingForm)
{
var client = GetProxy();
try
{
var request = new createShipmentRequest {integrationHeader = GetIntegrationHeader()};
var shipment = new requestedShipment();
// Shipment Type Code (Delivery or Return)
var shipmentType = new referenceDataType {code = shippingForm.ShippingType};
shipment.shipmentType = shipmentType;
// Service Type Code (1:24H 1st Class, 2: 48H 2nd Class, D: Special Delivery Guaranteed, H: HM Forces (BFPO), I: International, R: Tracked Returns, T: Tracked Domestic)
var serviceType = new referenceDataType {code = shippingForm.ServiceType};
shipment.serviceType = serviceType;
// Service Offering (See Royal Mail Service Offering Type Codes. Too Many To List)
var serviceOfferingTypeContainer = new serviceOfferingType();
var serviceOffering = new referenceDataType {code = shippingForm.ServiceOffering};
serviceOfferingTypeContainer.serviceOfferingCode = serviceOffering;
shipment.serviceOffering = serviceOfferingTypeContainer;
// Service Format Code
var serviceFormatTypeContainer = new serviceFormatType();
var serviceFormat = new referenceDataType {code = shippingForm.ServiceFormat};
serviceFormatTypeContainer.serviceFormatCode = serviceFormat;
shipment.serviceFormat = serviceFormatTypeContainer;
// Shipping Date
shipment.shippingDate = shippingForm.ShippingDate;
shipment.shippingDateSpecified = true;
shipment.signature = true;
shipment.signatureSpecified = true;
// Sender Reference Number (e.g. Invoice Number or RA Number)
shipment.senderReference = shippingForm.InvoiceNumber;
/*
* Service Enhancements
*/
var serviceEnhancements = new List<serviceEnhancementType>();
shipment.serviceEnhancements = serviceEnhancements.ToArray();
/*
* Recipient Contact Details
*/
var recipientContact = new contact();
recipientContact.complementaryName = shippingForm.Company;
recipientContact.name = shippingForm.Name;
if(!shippingForm.EmailAddress.Equals("")) {
var email = new digitalAddress {electronicAddress = shippingForm.EmailAddress};
recipientContact.electronicAddress = email;
}
if(!shippingForm.MobileNumber.Equals("")) {
var tel = new telephoneNumber();
var phoneRegex = new Regex(#"[^\d]");
tel.telephoneNumber1 = phoneRegex.Replace(shippingForm.MobileNumber, "");
tel.countryCode = "00" + shippingForm.CountryDiallingCode;
recipientContact.telephoneNumber = tel;
}
shipment.recipientContact = recipientContact;
/*
* Recipient Address
*
*/
var recipientAddress = new address
{
addressLine1 = shippingForm.AddressLine1,
addressLine2 = shippingForm.AddressLine2,
addressLine3 = shippingForm.AddressLine3,
addressLine4 = shippingForm.County,
postTown = shippingForm.Town
};
var country = new countryType();
var countryCode = new referenceDataType { code = shippingForm.CountryCode };
country.countryCode = countryCode;
recipientAddress.country = country;
recipientAddress.postcode = shippingForm.PostCode;
recipientAddress.stateOrProvince = new stateOrProvinceType {stateOrProvinceCode = new referenceDataType()};
shipment.recipientAddress = recipientAddress;
// Shipment Items
var items = new List<item> ();
foreach(var i in shippingForm.Items) {
var item = new item
{
numberOfItems = i.Products.Count.ToString(),
weight = new dimension
{
value = i.Weight*1000,
unitOfMeasure = new unitOfMeasureType {unitOfMeasureCode = new referenceDataType {code = "g"}}
}
};
items.Add(item);
}
if (shippingForm.ServiceType.Contains("international"))
{
var internationalInfo = new internationalInfo
{
shipperExporterVatNo = _config.GetVatNumber(),
documentsOnly = false,
shipmentDescription = "Invoice Number: " + shippingForm.InvoiceNumber,
invoiceDate = DateTime.Now,
termsOfDelivery = "EXW",
invoiceDateSpecified = true,
purchaseOrderRef = shippingForm.InvoiceNumber
};
var parcels = new List<parcel>();
foreach (var i in shippingForm.Items)
{
var parcel = new parcel
{
weight = new dimension
{
value = i.Weight*1000,
unitOfMeasure = new unitOfMeasureType
{
unitOfMeasureCode = new referenceDataType {code = "g"}
}
},
invoiceNumber = shippingForm.InvoiceNumber,
purposeOfShipment = new referenceDataType {code = "31"}
};
var contents = new List<contentDetail>();
foreach (var product in i.Products)
{
var contentDetail = new contentDetail
{
articleReference = product.Sku,
countryOfManufacture = new countryType
{
countryCode = new referenceDataType
{
code = product.CountryOfManufacture
}
},
currencyCode = new referenceDataType {code = product.CurrencyCode},
description = product.Name,
unitQuantity = product.Qty.ToString(),
unitValue = product.Price,
unitWeight = new dimension
{
value = Convert.ToSingle(product.Weight*1000),
unitOfMeasure = new unitOfMeasureType
{
unitOfMeasureCode = new referenceDataType {code = "g"}
}
}
};
contents.Add(contentDetail);
}
//Parcel.contentDetails = Contents.ToArray();
parcels.Add(parcel);
}
internationalInfo.parcels = parcels.ToArray();
shipment.internationalInfo = internationalInfo;
}
else
{
shipment.items = items.ToArray();
}
request.requestedShipment = shipment;
var response = client.createShipment(GetSecurityHeaderType(), request);
// Show Errors And Warnings
CheckErrorsAndWarnings(response.integrationFooter);
return response;
}
catch (TimeoutException e)
{
client.Abort();
MessageBox.Show("Request Timed Out: " + e.Message, "Request Timeout", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
}
catch (FaultException e)
{
client.Abort();
ShowSoapException(e);
}
catch (CommunicationException e)
{
client.Abort();
MessageBox.Show("A communication error has occurred: " + e.Message + " - " + e.StackTrace, "Communication Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
}
catch (Exception e)
{
client.Abort();
MessageBox.Show(e.Message, "Royal Mail Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
}
return null;
}
}
RoyalmailMessage.cs
class RoyalMailMessage : Message
{
public Message _message;
public RoyalMailMessage(Message message)
{
_message = message;
}
public override MessageHeaders Headers
{
get
{
return _message.Headers;
}
}
public override MessageProperties Properties
{
get
{
return _message.Properties;
}
}
public override MessageVersion Version
{
get
{
return _message.Version;
}
}
protected override void OnWriteStartBody(XmlDictionaryWriter writer)
{
writer.WriteStartElement("Body", "http://schemas.xmlsoap.org/soap/envelope/");
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
_message.WriteBodyContents(writer);
}
protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer)
{
writer.WriteStartElement("soapenv", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
writer.WriteAttributeString("xmlns", "v2", null, "http://www.royalmailgroup.com/api/ship/V2");
writer.WriteAttributeString("xmlns", "v1", null, "http://www.royalmailgroup.com/integration/core/V1");
writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
writer.WriteAttributeString("xmlns", "xsd", null, "http://www.w3.org/2001/XMLSchema");
}
}
RoyalMailMessageFormatter.cs
public class RoyalMailMessageFormatter : IClientMessageFormatter
{
private readonly IClientMessageFormatter _formatter;
public RoyalMailMessageFormatter(IClientMessageFormatter formatter)
{
_formatter = formatter;
}
public object DeserializeReply(Message message, object[] parameters)
{
return _formatter.DeserializeReply(message, parameters);
}
public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
{
var message = _formatter.SerializeRequest(messageVersion, parameters);
return new RoyalMailMessage(message);
}
}
RoyalMailIEndpointBehavior.cs
internal class RoyalMailIEndpointBehavior : IOperationBehavior
{
public void ApplyClientBehavior(OperationDescription description, ClientOperation proxy)
{
proxy.Formatter = new RoyalMailMessageFormatter(proxy.Formatter);
}
public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
{
}
public void Validate(OperationDescription operationDescription)
{
}
}
The error you are getting is basically because of the certificate.
Having said that, I think you should use the v2 of the API as although it is still awful, there are examples out there and you don't need to use a cert.
Rick Strahl has successfully changed the namespaces in the v2 version, see here https://weblog.west-wind.com/posts/2016/Apr/02/Custom-Message-Formatting-in-WCF-to-add-all-Namespaces-to-the-SOAP-Envelope .
There is one new Royal Mail Shipping API 2 available , after I've lost many hours try development the integration with Royal Mail I finally found a way. I'm sharing my project in the git.
https://github.com/americoa/RoyalMailShippingAPIV2

how to Update same member_id if Phone number and Country code exist in database

public class RegistrationController : ApiController
{
public DefaultRespons GetRegister(int os_id, string device_id, int country_code, long mobile_no)
{
LociDataClassesDataContext dc = new LociDataClassesDataContext();
registration reg = new registration();
reg.os_id = os_id;
reg.device_id = device_id;
reg.country_code = country_code;
reg.mobile_number = mobile_no;
reg.verification_code = new Random().Next(1000, 9999);
dc.registrations.InsertOnSubmit(reg);
dc.SubmitChanges();
Twilio.TwilioRestClient client = new Twilio.TwilioRestClient("ACcount", "token");
Twilio.SMSMessage message = client.SendSmsMessage("+16782493911", "+" + reg.country_code + "" + reg.mobile_number, "Your verification code for Locii is: " + reg.verification_code);
if (message.RestException != null)
Debug.WriteLine(message.RestException.Message);
return new DefaultRespons(1, "OK",Registration.getResponse(reg));
}
public DefaultRespons GetActivate(int registration_id, int verification_code)
{
LociDataClassesDataContext dc = new LociDataClassesDataContext();
registration reg = dc.registrations.Where(r => r.id == registration_id && r.verification_code == verification_code && r.registration_date==null).SingleOrDefault();
if (reg!=null)
{
List<registration> previous = dc.registrations.Where(r => r.mobile_number == reg.mobile_number && r.country_code == reg.country_code).ToList();
foreach (registration r in previous)
{
member mem = dc.members.Where(mb => mb.registration_id == r.id).SingleOrDefault();
if (mem!=null)
mem.online_status = -1;
}
member m = new member();
m.registration_id = reg.id;
m.online_status = 0;
reg.registration_date = DateTime.Now;
dc.members.InsertOnSubmit(m);
dc.SubmitChanges();
return new DefaultRespons(1, "Activated", Activation.getResponse(m));
}
else
{
return new DefaultRespons(1, "Failed", "");
}
}
Here is My code from which i am creating new Member_id . when i Enter following parameter and i activate from code then in response there is new Member_id id creating and it return . now i want when i register with same Phone number and country code whose Member id is already create i want to return same member_id it should not update new Member id please help me how to check the Phone number and country code already exist in database and return same member id. please help me i am not able to do this how to check .
Hi Anil try this sample code:
make required changes as per your code
public int CheckUser(int countrycode, long mobileno)
{
LociDataClassesDataContext dc = new LociDataClassesDataContext();
int id = from b in dc.registrations
where b.country_code.Equals(countrycode) && b.mobile_number.Equals(mobileno)
select b.registration_id;
return id;
}
public DefaultRespons GetRegister(int os_id, string device_id, int country_code, long mobile_no)
{
LociDataClassesDataContext dc = new LociDataClassesDataContext();
int reg_id = CheckUser(country_code, mobile_no);
if (reg_id == 0)
{
registration reg = new registration();
reg.os_id = os_id;
reg.device_id = device_id;
reg.country_code = country_code;
reg.mobile_number = mobile_no;
reg.verification_code = new Random().Next(1000, 9999);
dc.registrations.InsertOnSubmit(reg);
dc.SubmitChanges();
Twilio.TwilioRestClient client = new Twilio.TwilioRestClient("AC3c23fee017f23f5061a6b5d3be6f74da", "6fe81560f88f3850c5ad5d4a7b8a5f50");
Twilio.SMSMessage message = client.SendSmsMessage("+16782493911", "+" + reg.country_code + "" + reg.mobile_number, "Your verification code for Locii is: " + reg.verification_code);
if (message.RestException != null)
Debug.WriteLine(message.RestException.Message);
return new DefaultRespons(1, "OK", Registration.getResponse(reg));
}
else
{
//your code what you want to do with the reg_id
}
}
#Arijit - For best practice, please make sure to not include your auth token in your code examples, or at least make sure to reset it any time you share it. Thanks!

Categories

Resources