Trying to get data from wsdl using c# - c#

I have this c# code where i am trying to get data from a wsdl in visual studio .
The code is okay but when i try to get the data to written on notepad it just shows an empty space :
WindowsService1.ServiceReference1.GetModifiedBookingsOperationResponse getModbkgsResp;
using (var proxy = new WindowsService1.ServiceReference1.InventoryServiceClient())
{
int noofBookings = 1;
getModbkgsResp = proxy.GetModifiedBookings(getModBkgsReq);
WindowsService1.ServiceReference1.Booking[] bookings = new WindowsService1.ServiceReference1.Booking[noofBookings];
getModbkgsResp.Bookings = new WindowsService1.ServiceReference1.Booking[noofBookings];
getModbkgsResp.Bookings = bookings;
if (getModbkgsResp.Bookings != null)
{
for (int i = 0; i < bookings.Length; i++)
{
Booking bk = new WindowsService1.ServiceReference1.Booking();
getModbkgsResp.Bookings[i] = bk;
if (bk != null )
{
bookingSource = bk.BookingSource;
if (bk.BookingId == Bookingcode)
{
this.WriteToFile("Booking Source =" + bookingSource + "");
}
else
{
this.WriteToFile("Sorry could not find your source of booking");
}
}
else
{
this.WriteToFile("Looks like source is null " );
}
}
}
else
{
this.WriteToFile("ERROR: Booking details not returned from GetModifiedBookings! " +StartDate);
}
}

I'm not sure why you are using the new keyword to create items that should have been retrieved from the service. Naturally anything created with new will be initialized with default values and will not contain any data that was retrieved from the service.
My guess is your code should look more like this:
using (var proxy = new WindowsService1.ServiceReference1.InventoryServiceClient())
{
var response = proxy.GetModifiedBookings(getModBkgsReq);
if (response.Bookings == null)
{
this.WriteToFile("ERROR: Booking details not returned from GetModifiedBookings! " +StartDate);
return;
}
var booking = response.Bookings.SingleOrDefault( b => b.BookingId == bookingCode);
if (booking == null)
{
this.WriteToFile("Sorry could not find your source of booking");
return;
}
var bookingSource = booking.BookingSource;
this.WriteToFile("Booking Source =" + bookingSource + "");
}

Related

Entity saves ok but will not update record no matter what I do

Context is not saving to the database no matter what i do it will insert a new record fine but not save. This is using sql server and the user had permissions ot update data have already checked this
private void btnOk_Click(object sender, EventArgs e)
{
SourceContext SourceDal = new SourceContext();
Appointment _appointment = new Appointment();
int errorCount = 0;
Patient _patient = new Patient();
_patient = SourceDal.getPatientByPatientId(txtPatientId.Text);
_patient.SSN = txtSSN.Text;
_patient.FirstName = txtPatientFirstName.Text;
_patient.LastName = txtPatientLastName.Text;
_patient.Middle = txtPatientMiddle.Text;
_patient.AddressOne = txtPatientAddressOne.Text;
_patient.City = txtPatientCity.Text;
_patient.State = txtPatientState.Text;
_patient.ZipCode = txtPatientZip.Text;
_patient.HomePhone = txtPatientHomePhone.Text;
_patient.WorkPhone = txtPatientWorkPhone.Text;
_patient.CellPhone = txtPatientCellPhone.Text;
if (rBtnHomePhone.Checked == true)
_patient.ApptPhone = txtPatientHomePhone.Text;
if (rBtnHomePhone.Checked == true)
_patient.ApptPhone = txtPatientHomePhone.Text;
if (rBtnWorkPhone.Checked == true)
_patient.ApptPhone = txtPatientWorkPhone.Text;
_patient.BirthDate = dtBirthDate.DateTime;
_patient.emailAddress = txtPatientEmail.Text;
_patient.Race = (int)dpRace.SelectedValue;
_patient.Ethnicity = (int)dpEthnicity.SelectedValue;
_patient.Language = (int)dpLanguages.SelectedValue;
_patient.AlertNote = txtPatientNotes.Text;
if (dpGender.Text == "")
{
dpGender.Focus();
errorCount = 1;
lblGenderRequired.Text = "* Gender is required.";
}
else
{
errorCount = 0;
lblGenderRequired.Visible = false;
}
_patient.Gender = dpGender.Text.Substring(0, 1);
_patient.PatientID = txtPatientId.Text;
txtPatientFirstName.Text = _patient.FirstName;
txtPatientLastName.Text = _patient.LastName;
// IF ITS SAVE NEW GO AHEAD ADD IT TO THE CONTEXT.
SourceDal.AddToPatient(_patient);
}
Add to paitent has the following
public void AddToPatient(Patient newPatient)
{
using (var myContext = new SMBASchedulerEntities(this.Connectionstring))
{
myContext.Patients.Add(newPatient);
if (newPatient.ID == 0)
{
myContext.Entry(newPatient).State = EntityState.Added;
}
else
{
myContext.Entry(newPatient).State = EntityState.Modified;
}
try
{
myContext.SaveChanges();
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Console.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
}
}
}
}
}
It adds in the record fine but it just wont save the current record no matter what i do even though all the details are correct. But when i reload the form and the application the update is not there the email address is not saved no are any the other updates.
I suspect I'm not familiar with that entity framework, as I'm unfamiliar with the some of that syntax, but you should be able to use something like this:
public void AddToPatient(Patient newPatient)
{
SMBASchedulerEntities dbContext = new SMBASchedulerEntities();
if (newPatient.ID.ToString() != "0")
{//Update the record
Patient updatePatient = dbContext.Patients.Single(p => p.ID == newPatient.ID);
updatePatient.FirstName = newPatient.FirstName;
updatePatient.LastName = newPatient.LastName;
...
...
dbContext.SubmitChanges();
}
else
{//Insert a new record
Patient insertPatient = new Patient();
insertPatient.FirstName = newPatient.FirstName;
insertPatient.LastName = newPatient.LastName;
...
...
dbContext.Patients.InsertOnSubmit(insertPatient);
dbContext.SubmitChanges();
}
}
To put this another way, check to see if you need to insert or update a new patient first, before inserting it every time.

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

How to implement "apply credit" to existing invoices if credits are available for that customer via .Net C# code by using Interop.QBFC13Lib.dll?

I got stuck when trying to implement the "apply credit" functionality of Quickbooks to existing invoices if credit is available for that customer. I am able to do it via Quickbooks Desktop UI but not getting the way to implement it via a .Net integrated app, written in C#. Can any one please guide on this.
Code which I am using to implement "apply credit" to Quickbooks via C# code.
I am getting the error: "QuickBooks found an error when parsing the provided XML text stream." with below code.
public void ApplyCreditsOnPrePayInvoices()
{
// open connection and begin session before data fetch - intentionally skipped this code
IMsgSetRequest msgset = null;
ICreditMemoQuery creditMemoQuery = null;
string sCustomerName = string.Empty;
if (this.GetConnectedToQB()) //this is the method call to login to quickbooks desktop
{
try
{
// during data fetch
msgset = m_sessionManager.CreateMsgSetRequest("US", 8, 0);
creditMemoQuery = msgset.AppendCreditMemoQueryRq();
creditMemoQuery.ORTxnQuery.TxnFilter.ORDateRangeFilter.ModifiedDateRangeFilter.FromModifiedDate.SetValue(new DateTime(2012, 3, 31), false);
IMsgSetResponse msgRes = m_sessionManager.DoRequests(msgset);
IResponseList responseList = msgRes.ResponseList;
if (responseList.Count > 0)
{
IResponse response = responseList.GetAt(0);
ICreditMemoRetList creditMemoList = response.Detail as ICreditMemoRetList;
if (creditMemoList == null)
{
return;
}
for (int i = 0; i <= creditMemoList.Count - 1; i++)
{
ICreditMemoRet qbCreditMemo = creditMemoList.GetAt(i);
if (this.GetQBCustomerListId(qbCreditMemo.CustomerRef.FullName.GetValue()) != string.Empty)
{
m_requestMsgSet.ClearRequests();
m_requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue;
IInvoiceAdd invoiceAddRq = m_requestMsgSet.AppendInvoiceAddRq();
invoiceAddRq.CustomerRef.FullName.SetValue(qbCreditMemo.CustomerRef.FullName.GetValue());
ISetCredit SetCredit1 = invoiceAddRq.SetCreditList.Append();
SetCredit1.CreditTxnID.SetValue(qbCreditMemo.TxnID.GetValue());
SetCredit1.AppliedAmount.SetValue(qbCreditMemo.TotalAmount.GetValue());
IMsgSetResponse responseSetInvoice = m_sessionManager.DoRequests(m_requestMsgSet);
DataSet dsInvoice = this.GetExtractResponseFromQB(responseSetInvoice);
string sQueryResponse = Stringcl.GetValue(dsInvoice.Tables["InvoiceAddRs"].Rows[0]["statusMessage"]);
if (sQueryResponse == "Status OK")
{
Console.WriteLine("Credit no.:" + qbCreditMemo.TxnID.GetValue() + " Customer:" + qbCreditMemo.CustomerRef.FullName.GetValue() + " Total:" + qbCreditMemo.TotalAmount.GetValue());
}
}
}
}
}
catch (Exception ex)
{
string ss = ex.Message;
//handle exception here
}
finally
{
if (msgset != null)
{
Marshal.FinalReleaseComObject(msgset);
}
if (creditMemoQuery != null)
{
Marshal.FinalReleaseComObject(creditMemoQuery);
}
}
}
// end session and close connection after data fetch - intentionally skipped this code
}
Thanks in advance!!
I got solution by using below function:-
public void ApplyCreditsOnPrePayInvoices(string sMonth, string sYear)
{
IMsgSetRequest IMsgSetRequestToQB = null;
ICreditMemoQuery ICreditMemoQueryToQB = null;
string sInvoiceTxnId = string.Empty;
string sInvoiceNumber = string.Empty;
if (this.GetConnectedToQB())
{
try
{
IMsgSetRequestToQB = m_sessionManager.CreateMsgSetRequest("US", 8, 0);
ICreditMemoQueryToQB = IMsgSetRequestToQB.AppendCreditMemoQueryRq();
ICreditMemoQueryToQB.ORTxnQuery.TxnFilter.ORDateRangeFilter.ModifiedDateRangeFilter.FromModifiedDate.SetValue(DateTimecl.GetValue("1." + sMonth + sYear), true);
IMsgSetResponse IMsgSetResponseFromQB = m_sessionManager.DoRequests(IMsgSetRequestToQB);
IResponseList ICreditListMemoAvailable = IMsgSetResponseFromQB.ResponseList;
if (ICreditListMemoAvailable.Count > 0)
{
string sCustomerListIdQB = string.Empty;
string sCustomerAccountNumber = string.Empty;
string sQBImportPrepayAccounts = Path.Combine(Environment.CurrentDirectory, sMonth + sYear, "Step11_QBImport_PrepayAccounts.csv");
DataTable dtQBImportPrepayAccounts = Utilcl.GetDataTableFromCSVFile(sQBImportPrepayAccounts);
IResponse ICreditMemoAvailable = ICreditListMemoAvailable.GetAt(0);
ICreditMemoRetList iCreditMemoList = ICreditMemoAvailable.Detail as ICreditMemoRetList;
if (iCreditMemoList != null)
{
for (int iCtr = 0; iCtr <= iCreditMemoList.Count - 1; iCtr++)
{
ICreditMemoRet ICreditMemo = iCreditMemoList.GetAt(iCtr);
DataRow[] drInvoiceNos = dtQBImportPrepayAccounts.Select("RefNumber = '" + ICreditMemo.RefNumber.GetValue() + "'");
if (drInvoiceNos.Length > 0)
{
sInvoiceNumber = Stringcl.GetValue(drInvoiceNos[0]["RefNumber"]);
m_requestMsgSet.ClearRequests();
m_requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue;
IReceivePaymentAdd IReceivePayment = m_requestMsgSet.AppendReceivePaymentAddRq();
sInvoiceTxnId = this.GetQBInvoiceTxnIDList(ICreditMemo.CustomerRef.FullName.GetValue()); //To get the Transaction ID of Invoice
IReceivePayment.CustomerRef.FullName.SetValue(Stringcl.GetValue(ICreditMemo.CustomerRef.FullName.GetValue()));
IAppliedToTxnAdd IAppliedToTxnAddress = IReceivePayment.ORApplyPayment.AppliedToTxnAddList.Append();
IAppliedToTxnAddress.TxnID.SetValue(sInvoiceTxnId);
ISetCredit ISetCreditToInvoice = IAppliedToTxnAddress.SetCreditList.Append();
ISetCreditToInvoice.CreditTxnID.SetValue(ICreditMemo.TxnID.GetValue());
ISetCreditToInvoice.AppliedAmount.SetValue(ICreditMemo.TotalAmount.GetValue());
IMsgSetResponse responseApplyCredit = m_sessionManager.DoRequests(m_requestMsgSet);
DataSet dsInvoice = this.GetExtractResponseFromQB(responseApplyCredit);
string sQueryResponse = Stringcl.GetValue(dsInvoice.Tables["ReceivePaymentAddRs"].Rows[0]["statusMessage"]);
if (sQueryResponse != "Status OK")
{
Utilcl.LogMessage("QB Credit Memo Query Response: " + sQueryResponse);
}
}
}
}
}
}
catch (Exception ex)
{
Utilcl.LogMessage(ex);
}
finally
{
if (IMsgSetRequestToQB != null)
{
Marshal.FinalReleaseComObject(IMsgSetRequestToQB);
}
if (ICreditMemoQueryToQB != null)
{
Marshal.FinalReleaseComObject(ICreditMemoQueryToQB);
}
}
}
}

Netsuite List all subsidiary items using soap webservice

I need to reference a customer to a subsidiary in netsuite. I am using c# soap api. Is there a way to loop over all subsidiary items in netsuite in c# and select the one i need.
It would be something like this:
var sub = new SubsidiarySearchBasic();
var res = netSuiteService.search(sub);
if (res.status.isSuccess)
{
if (res.totalPages == res.pageIndex)
{
var result = res.recordList.ToList().Any() ? res.recordList.ToList().Cast<Subsidiary>().ToList() : null;
}
else
{
var resultados = res.recordList.ToList().Cast<Invoice>().ToList();
for (var i = 2; i <= res.totalPages; i++)
{
var resPages = netSuiteService.searchMoreWithId(res.searchId, i);
if (resPages.status.isSuccess)
{
resultados.AddRange(res.recordList.ToList().Cast<Invoice>().ToList());
}
}
}
}
else
{
throw new Exception(string.Join(",", res.status.statusDetail.ToList()));
}

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