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.
Related
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;
}
}
I am new in stripe, how can we set default payment method in stripe.
And can we pass cardId/sourceId to charge customer along with customerId.
Code:-
private static async Task<string> ChargeCustomer(string customerId)
{
return await System.Threading.Tasks.Task.Run(() =>
{
var myCharge = new StripeChargeCreateOptions
{
Amount = 50,
Currency = "gbp",
Description = "Charge for property sign and postage",
CustomerId = customerId
};
var chargeService = new StripeChargeService();
var stripeCharge = chargeService.Create(myCharge);
return stripeCharge.Id;
});
}
And 1 more question, how to get charge-list, I am using below code but getting exception(conversion error):-
private IEnumerable<StripeCharge> GetChargeList()
{
var chargeService = new StripeChargeService();
return chargeService.List();
}
This is what I ended up doing. Not sure why Stripe Checkout didn't set the card for the subscription setup as the default. Anyway, this fires triggered from the payment_intent.succeeded web hook. Sure there is a better way, but...
var customerService = new CustomerService(Configs.STRIPE_SECRET_KEY);
var c = customerService.Get(pi.CustomerId);
if (!string.IsNullOrEmpty(c.InvoiceSettings.DefaultPaymentMethodId)) {
status = "already has default payment method, no action";
hsc = HttpStatusCode.OK;
return;
}
var paymentMethodService = new PaymentMethodService(Configs.STRIPE_SECRET_KEY);
var lopm = paymentMethodService.ListAutoPaging(options: new PaymentMethodListOptions {
CustomerId = pi.CustomerId,
Type = "card"
});
if (!lopm.Any()) {
status = "customer has no payment methods";
hsc = HttpStatusCode.BadRequest;
return;
}
var pm = lopm.FirstOrDefault();
customerService.Update(pi.CustomerId, options: new CustomerUpdateOptions {
InvoiceSettings = new CustomerInvoiceSettingsOptions {
DefaultPaymentMethodId = pm.Id
}
});
hsc = HttpStatusCode.OK;
return;
We can pass cardId/BankAccountId/TokenId/SourceId in SourceTokenOrExistingSourceId property of StripeChargeCreateOptions,
private static async Task<string> ChargeCustomer(string customerId, string cardId)
{
try
{
return await System.Threading.Tasks.Task.Run(() =>
{
var myCharge = new StripeChargeCreateOptions
{
Amount = 50,
Currency = "gbp",
Description = "Charge for property sign and postage",
CustomerId = customerId,
SourceTokenOrExistingSourceId = cardId
};
var chargeService = new StripeChargeService();
var stripeCharge = chargeService.Create(myCharge);
return stripeCharge.Id;
});
}
catch(Exception ex)
{
return "";
}
}
To set/change default payment method:-
public void ChangeDefaultPayment(string customerId, string sourceId)
{
var myCustomer = new StripeCustomerUpdateOptions();
myCustomer.DefaultSource = sourceId;
var customerService = new StripeCustomerService();
StripeCustomer stripeCustomer = customerService.Update(customerId, myCustomer);
}
Still looking for how to get charge-list.
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.
Here, I want the list "User" as a response. But it contains Message also. I want the message to be printed only once. Currently it is printing user.count times.
for (int i = 0; i < user.Count; i++)
{
if (user[i].Message == "Success")
{
resp = new HttpResponseMessage { Content = new ObjectContent(typeof(List<GetUserList>), user, GlobalConfiguration.Configuration.Formatters.JsonFormatter) };
}
else
{
resp = new HttpResponseMessage { Content = new StringContent("[{\"Message\":\"" + user[i].Message + "\"}]", System.Text.Encoding.UTF8, "application/json") };
}
}
The result should be like this:
{
"message": " Successful",
"supervisorlist": [
{
" userID ": "654",
" forename ": "John"
},
{
" userID ": "655",
" forename ": "Jack"
}
]
}
example for Success
var responseObj = new { message = "Successful", supervisorlist = users };
resp = new HttpResponseMessage
{
Content = new StringContent(JsonConvert.SerializeObject(responseObj),
System.Text.Encoding.UTF8, "application/json")
};
bool includeMessage = users.Any(u => u.Message == "Success");
object content = null;
if(includeMessage) {
content = new { message = "Success", supervisorlist = users };
} else {
content = new { supervisorlist = users };
}
resp = new HttpResponseMessage {
Content = new StringContent(JsonConvert.SerializeObject(content), System.Text.Encoding.UTF8, "application/json")
};
I am using Facebook.dll i.s FacebookClient , Mainly I want to read Facebook user mail box I have auth token saved in db.
Select messages (all) from mail box where I can mention start date and end date
Save all messages in db
I have used
dynamic result = objFacebookClient.Get("fql",
new { q = "SELECT message_id, author_id, body, created_time FROM message WHERE thread_id IN (SELECT thread_id FROM thread WHERE folder_id = 0)" });
Is it possible get result as
Message - Content of message
Send t o- Sender name and id
Receive By - Name and id
Create Date - Message create date
Code is here
dynamic result = objFacebookClient.Get("fql",
new { q = "SELECT message_id, author_id, body, created_time FROM message WHERE thread_id IN (SELECT thread_id FROM thread WHERE folder_id = 0)" });
List<Model.FacebookUserMessageInfo> objFacebookMessageList = new List<Model.FacebookUserMessageInfo>();
if (result != null)
{
Model.FacebookUserMessageInfo objFacebookMessage = null;
var values = result.Values;
var TotalResult = (((System.Collections.Generic.Dictionary<string, object>.ValueCollection)values).ToList()[0]);
var TotalMessagesData = (JsonArray)TotalResult;
if (TotalMessagesData != null)
{
foreach (var Messages in TotalMessagesData)
{
objFacebookMessage = new Model.FacebookUserMessageInfo();
objFacebookMessage.MessageText = (((JsonObject)Messages)["body"]).ToString();
objFacebookMessage.ActionUserID = Convert.ToInt64(((JsonObject)Messages)["author_id"]);
if (objFacebookMessage.ActionUserID == CurrentUserId)
{
objFacebookMessage.MessageType = Core.Enum.FacebookMessageType.Sent.ToString();
}
else
{
objFacebookMessage.MessageType = Core.Enum.FacebookMessageType.Receive.ToString();
}
objFacebookMessage.FacebookUserId = FacebookUserId;
var MessageSecond = (((JsonObject)Messages)["created_time"]).ToString();
var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
objFacebookMessage.CreatedDate = dateTime.AddSeconds(double.Parse(MessageSecond));
objFacebookMessageList.Add(objFacebookMessage);
}
}
}
Thanks in advance
I got my solution
public class Facebook
{
#region Private Properties
private string ClientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];
private string ClientSecret = System.Configuration.ConfigurationManager.AppSettings["ClientSecret"];
#endregion
#region Public Methods
public string GetLongLifeAccessToken(string ExistingToken)
{
try
{
string Data = string.Empty;
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=fb_exchange_token&fb_exchange_token={2} ",
ClientId, ClientSecret, ExistingToken);
System.Net.HttpWebRequest request = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;
using (System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse)
{
System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Data = sr.ReadToEnd();
Data = HttpUtility.ParseQueryString(Data)["access_token"];
}
return Data;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public List<Model.FacebookUserMessageInfo> ReadFacebookMailbox(string AuthToken, long? CurrentUserDefaultFacebookId, DateTime? LastProcessedDate, DateTime CurrentDate, int FacebookUserId)
{
try
{
FacebookClient objFacebookClient;
List<Model.FacebookUserMessageInfo> objFacebookMessageList;
objFacebookClient = new FacebookClient(AuthToken);
try
{
objFacebookClient.Get("me");
}
catch (Exception ex)
{
throw new Exception(ErrorType.UnableToAuthorizFacebookUser.ToString());
}
TimeSpan t = LastProcessedDate.Value - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
int timestamp = (int)t.TotalSeconds;
dynamic result = objFacebookClient.Get("fql",
new { q = "SELECT message_id, author_id, viewer_id, body, created_time FROM message WHERE thread_id IN (SELECT thread_id FROM thread WHERE folder_id = 0) AND created_time >= " + timestamp.ToString() });
objFacebookMessageList = new List<Model.FacebookUserMessageInfo>();
if (result != null)
{
Model.FacebookUserMessageInfo objFacebookMessage = null;
var values = result.Values;
var TotalResult = (((System.Collections.Generic.Dictionary<string, object>.ValueCollection)values).ToList()[0]);
var TotalMessagesData = (JsonArray)TotalResult;
if (TotalMessagesData != null)
{
foreach (var Messages in TotalMessagesData)
{
/*author_id = The ID of the user who wrote this message.*/
/*viewer_id = The ID of the user whose Inbox you are querying*/
objFacebookMessage = new Model.FacebookUserMessageInfo();
objFacebookMessage.MessageText = (((JsonObject)Messages)["body"]).ToString();
long author_id = Convert.ToInt64(((JsonObject)Messages)["author_id"]);
long viewer_id = Convert.ToInt64(((JsonObject)Messages)["viewer_id"]);
if (author_id == viewer_id)
{
objFacebookMessage.MessageType = Core.Enum.FacebookMessageType.Sent.ToString();
}
else
{
objFacebookMessage.MessageType = Core.Enum.FacebookMessageType.Receive.ToString();
}
objFacebookMessage.ActionUserID = author_id;
objFacebookMessage.FacebookUserId = FacebookUserId;
var MessageSecond = (((JsonObject)Messages)["created_time"]).ToString();
var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
objFacebookMessage.CreatedDate = dateTime.AddSeconds(double.Parse(MessageSecond));
objFacebookMessageList.Add(objFacebookMessage);
}
}
}
if (objFacebookMessageList.Count > 0)
{
objFacebookMessageList = objFacebookMessageList.Where(fm => fm.CreatedDate >= LastProcessedDate && fm.CreatedDate <= CurrentDate).ToList();
objFacebookMessageList.ForEach(item =>
{
var Auther = objFacebookClient.Get("https://graph.facebook.com/" + item.ActionUserID.ToString());
if (Auther != null)
{
item.ActionUserName = ((JsonObject)Auther)["name"].ToString();
}
else
{
item.ActionUserName = null;
}
});
}
return objFacebookMessageList;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
#endregion
}
If i understand what you want the answer is:
you need to create a class, FacebookMessage:
class FacebookMessage
{
public int SenderID { get; set; }
public int AddresseeID { get; set; }
public string SenderName { get; set; }
public string AddresseeName { get; set; }
public string Message { get; set; }
public DateTime CreateDate { get; set; }
public FacebookMessage()
{
SenderID = 0;
AddresseeID = 0;
SenderName = "";
AddresseeName = "";
Message = "";
}
}
and use this FQL:
dynamic result = objFacebookClient.Get("fql",
new { q = "SELECT body, author_id, viewer_id, created_time FROM message WHERE thread_id IN (SELECT thread_id FROM thread WHERE folder_id = 0)" });
After getting this info and save it in the FacebookMessage and run another query for each message:
FacebookMessage faceMsg = null;
var values = result.Values;
var TotalResult = (((System.Collections.Generic.Dictionary<string, object>.ValueCollection)values).ToList()[0]);
var TotalMessagesData = (JsonArray)TotalResult;
if (TotalMessagesData != null)
{
foreach (var Messages in TotalMessagesData)
{
faceMsg= new FacebookMessage();
faceMsg.Message = (((JsonObject)Messages)["body"]).ToString();
faceMsg.SenderID = Convert.ToInt64(((JsonObject)Messages)["author_id"]);
faceMsg.AddresseeID = Convert.ToInt64(((JsonObject)Messages)["viewer_id"]);
var MessageSecond = (((JsonObject)Messages)["created_time"]).ToString();
var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
faceMsg.CreatedDate = dateTime.AddSeconds(double.Parse(MessageSecond));
result = objFacebookClient.Get("fql",
new { q = "SELECT name FROM user WHERE uid = " + faceMsg.SenderID });
var values = result.Values;
faceMsg.SenderName = values.name; // Not tested, but should be something like that.
result = objFacebookClient.Get("fql",
new { q = "SELECT name FROM user WHERE uid = " + faceMsg.AddresseeID });
var values = result.Values;
faceMsg.AddresseeName= values.name; // Not tested, but should be something like that.
faceMsgList.Add(objFacebookMessage);
}
}
It is recommended to split the querys that get the names to diffrent methods.