SaveChanges() doesn't insert any records to database - c#

I'm using Entity Framework to add new records to the database, everything goes ok without any errors, but I don't see the new record in the database.
Update code works, but insert code doesn't work. No errors appear, but no records are inserted into the database.
My code :
var DBs2 = ConnectionTools.OpenConn();
DBs2.Configuration.AutoDetectChangesEnabled = false;
DBs2.Configuration.ValidateOnSaveEnabled = false;
var resList = CreatedSerials.Where(u => u.Item4 == VID).ToList();
foreach (var r in resList)
{
// if serial id ==0 => new then add it as new
if ( r.Item7 == 0)
{
try
{
var purchasesItemSerials = new purchases_item_seriels()
{
pitem_ID = pitem_ID,
stitems_ID = r.Item1,
pmain_ID = PurchasesID,
pitem_virtualID = r.Item4,
pis_CustomSerial = r.Item2,
pis_ExpireDate = r.Item3,
pis_Statues = 0,
ss_StoreID = Convert.ToInt32(gridView1.GetRowCellValue(ItemImdex, "storeID")),
Purchases_Price = Convert.ToDecimal(gridView1.GetRowCellValue(ItemImdex, "item_NetSmallestUnitPrice")),
};
ss.Add(purchasesItemSerials);
}
catch (Exception eeeeee)
{
Msg.Show("", eeeeee.ToString(), 0);return;
}
}
else
{
var DBs350 = ConnectionTools.OpenConn();
var UpdateSerial = DBs350.purchases_item_seriels.Find(r.Item7);
UpdateSerial.pitem_ID = pitem_ID;
UpdateSerial.stitems_ID = r.Item1;
UpdateSerial. pmain_ID = PurchasesID;
UpdateSerial.pitem_virtualID = r.Item4;
UpdateSerial.pis_CustomSerial = r.Item2;
UpdateSerial.pis_ExpireDate = r.Item3;
UpdateSerial.pis_Statues = r.Item6;
UpdateSerial.ss_StoreID = Convert.ToInt32(gridView1.GetRowCellValue(ItemImdex, "storeID"));
UpdateSerial.Purchases_Price = Convert.ToDecimal(gridView1.GetRowCellValue(ItemImdex, "item_NetSmallestUnitPrice"));
DBs350.SaveChanges();
}
}
try
{
DBs2.purchases_item_seriels.AddRange(ss);
DBs2.SaveChanges();
}
catch (Exception eeeeee)
{
Msg.Show("", eeeeee.ToString(), 0);return;
}
I also tried :
DBs2.Configuration.AutoDetectChangesEnabled = true;
DBs2.Configuration.ValidateOnSaveEnabled = true;
but again: no data is inserted, no errors appear
I also tried :
int returnCode = DBs2.SaveChanges();
and returnCode = 0
**I also tried : inserting just a single item then SaveChanges **
// if this serial is new
var NewSerialresList = CreatedSerials.Where(u => u.Item4 == VID && u.Item7 == 0).ToList();
if (NewSerialresList.Count() > 0)
{
var ss = new List<purchases_item_seriels>();
foreach (var r in NewSerialresList)
{
try
{
mrsalesdbEntities DBs002 = new mrsalesdbEntities();
var purchasesItemSerials = new purchases_item_seriels()
{
pitem_ID = pitem_ID,
stitems_ID = r.Item1,
pmain_ID = PurchasesID,
pitem_virtualID = r.Item4,
pis_CustomSerial = r.Item2,
pis_ExpireDate = r.Item3,
pis_Statues = 0,
ss_StoreID = Convert.ToInt32(gridView1.GetRowCellValue(ItemImdex, "storeID")),
Purchases_Price = Convert.ToDecimal(gridView1.GetRowCellValue(ItemImdex, "item_NetSmallestUnitPrice")),
};
//ss.Add(purchasesItemSerials);
DBs002.purchases_item_seriels.Add(purchasesItemSerials);
DBs002.SaveChanges();
}
catch (Exception ex)
{
Msg.Show("", ex.ToString(), 0);
}
}
int CC = ss.Count();
}
i use this function to change the connection variables at run-time :
public static mrsalesdbEntities OpenConn()
{
mrsalesdbEntities MrSalesContext = new mrsalesdbEntities();
MrSalesContext.ChangeDatabase
(
initialCatalog: myconn.database,
port: Convert.ToUInt32( myconn.port),
userId: myconn.uid,
password: myconn.password,
dataSource: myconn.server
);
return MrSalesContext;
}
public static void ChangeDatabase(
this DbContext source,
string initialCatalog = "",
uint port = 3307,
string dataSource = "",
string userId = "",
string password = "",
bool integratedSecuity = true,
string configConnectionStringName = "mrsalesdbEntities")
/* this would be used if the
* connectionString name varied from
* the base EF class name */
{
try
{
// use the const name if it's not null, otherwise
// using the convention of connection string = EF contextname
// grab the type name and we're done
var configNameEf = string.IsNullOrEmpty(configConnectionStringName)
? source.GetType().Name
: configConnectionStringName;
// add a reference to System.Configuration
var entityCnxStringBuilder = new EntityConnectionStringBuilder
(System.Configuration.ConfigurationManager
.ConnectionStrings[configNameEf].ConnectionString);
// init the sqlbuilder with the full EF connectionstring cargo
var sqlCnxStringBuilder = new MySqlConnectionStringBuilder
(entityCnxStringBuilder.ProviderConnectionString);
// only populate parameters with values if added
if (!string.IsNullOrEmpty(initialCatalog))
sqlCnxStringBuilder.Database = initialCatalog;
if ((port) != 0)
sqlCnxStringBuilder.Port = port;
if (!string.IsNullOrEmpty(dataSource))
sqlCnxStringBuilder.Server = dataSource;
if (!string.IsNullOrEmpty(userId))
sqlCnxStringBuilder.UserID = userId;
if (!string.IsNullOrEmpty(password))
sqlCnxStringBuilder.Password = password;
// set the integrated security status
//sqlCnxStringBuilder.IntegratedSecurity = integratedSecuity;
// now flip the properties that were changed
source.Database.Connection.ConnectionString
= sqlCnxStringBuilder.ConnectionString;
}
catch (Exception ex)
{
// set log item if required
}
}
}

Related

Modified entity is not applied into the database

I am trying to update loan balance based on the payment made by a member.
Payment goes well and it is inserted as expected but during the update of the table LOANBAl, nothing is modified, bellow is my code:
public void UpdateLoanBal(MPAreceipting mpa, string id)
{
using (BOSAEntities db = new BOSAEntities())
{
General gn = new General();
gn.GetUser();
gn.GetServerDate();
LoanRepayment lr = new LoanRepayment();
lr.GetMemberDeduction(loanno);
var lOANBAL = db.LOANBALs.Find(id);
var lb = new LOANBAL();
lb.AuditID = gn.sysUser;
lb.AuditTime = gn.serverDate;
lb.Balance = Convert.ToDecimal(lr.loanBalance);
lb.IntrOwed = Convert.ToDecimal(lr.intOwed);
lb.LastDate = mpa.dateDeposited;
db.Entry(lOANBAL).State = EntityState.Modified;
db.SaveChanges();
}
}
I used the lOANBAL which is an entity and update its properties.
public void UpdateLoanBal(MPAreceipting mpa, string id)
{
var db = new BOSAEntities();
using (var dbContextTransaction = db.Database.BeginTransaction())
{
try
{
var lOANBAL = db.LOANBALs.Find(loanno);
General gn = new General();
gn.GetUser();
gn.GetServerDate();
LoanRepayment lr = new LoanRepayment();
lr.GetMemberDeduction(loanno);
lOANBAL.LoanNo = loanno;
lOANBAL.AuditID = gn.sysUser;
lOANBAL.AuditTime = gn.serverDate;
lOANBAL.Balance = Convert.ToDecimal(lr.loanBalance);
lOANBAL.IntrOwed = Convert.ToDecimal(lr.intOwed);
lOANBAL.LastDate = mpa.dateDeposited;
lOANBAL.TransactionNo=lr.
db.Entry(lOANBAL).State = EntityState.Modified;
db.SaveChanges();
dbContextTransaction.Commit();
}
catch (DbEntityValidationException Exc)
{
dbContextTransaction.Rollback();
string errormessage = string.Join(";",
Exc.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage));
throw new DbEntityValidationException(errormessage);
}
}
}

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.

Validation error when attempting to SaveChanges to table

I am rather new to the whole programming with C# and I stumbled upon a small problem that I just cannot solve.
I start up the software the code below is programmed into and it is working well until it reaches the SaveChanges call and it throws an error:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
I have already attempted to inspect EntityValidationErrors, but it doesn't want to show me any errors at all. So I am turning to you all to find some answers.
//
// GET: /Installningar/FoxImportTidning
public async Task<ActionResult> FoxImportTidning()
{
Tidning tidning = new Tidning();
SaveTidningToDatabase("C:/Backup/Prenback/backuptidning.xls");
return View();
}
//
// POST: /Installningar/FoxImportTidning
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> FoxImportTidning(Tidning Id)
{
if (ModelState.IsValid)
{
db.Entry(Id).State = EntityState.Modified;
await db.SaveChangesAsync();
Main.PopulateGlobalInst();
ViewBag.SaveMsg = "Sparat!";
return RedirectToAction("Main", "Main", new { Id = Id.Id });
}
return View(Id);
}
private ApplicationDbContext databas6 = new ApplicationDbContext();
private string SaveTidningToDatabase(string filePath)
{
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
using (OleDbCommand cmd = new OleDbCommand("Select * from [backuptidning$]", excelConnection))
{
excelConnection.Open();
var tidningLista = new List<Tidning>();
databas6.Tidnings.Clear();
databas6.SaveChanges();
using (OleDbDataReader dReader = cmd.ExecuteReader())
do
{
while (dReader.Read())
{
Object[] tidninginfo = new Object[45];
int id = Convert.ToInt32(dReader[0]);
string namn = Convert.ToString(dReader[1]);
string datadir = Convert.ToString(dReader[2]);
string adr1 = Convert.ToString(dReader[3]);
string adr2 = Convert.ToString(dReader[4]);
string regnr = Convert.ToString(dReader[5]);
string tel = Convert.ToString(dReader[6]);
string pg = Convert.ToString(dReader[7]);
string bg = Convert.ToString(dReader[8]);
string villkor = Convert.ToString(dReader[9]);
int sista_nr = Convert.ToInt32(dReader[10]);
int faktavg = Convert.ToInt32(dReader[11]);
int vilande = Convert.ToInt32(dReader[12]);
int listlopnr = Convert.ToInt32(dReader[13]);
int faktnr = Convert.ToInt32(dReader[14]);
decimal moms = Convert.ToDecimal(dReader[15]);
int avipriskod = Convert.ToInt32(dReader[16]);
DateTime? inbetdat = null;
try
{
inbetdat = Convert.ToDateTime(dReader[17]);
}
catch { }
int period = Convert.ToInt32(dReader[18]);
string avityp = Convert.ToString(dReader[19]);
DateTime? sistavidat = null;
try
{
sistavidat = Convert.ToDateTime(dReader[20]);
}
catch { }
DateTime? fromdatum = null;
try
{
fromdatum = Convert.ToDateTime(dReader[21]);
}
catch { }
DateTime? tomdatum = null;
try
{
tomdatum = Convert.ToDateTime(dReader[22]);
}
catch { }
int fromprennr = Convert.ToInt32(dReader[23]);
int tomprennr = Convert.ToInt32(dReader[24]);
string databasversion = Convert.ToString(dReader[25]);
int nummerperiod = Convert.ToInt32(dReader[26]);
int nolastyear = Convert.ToInt32(dReader[27]);
int nonextyear = Convert.ToInt32(dReader[28]);
string dubbelnummer = Convert.ToString(dReader[29]);
bool skrivetik = Convert.ToBoolean(dReader[30]);
bool utrmomsavdrag = Convert.ToBoolean(dReader[31]);
bool buntning = Convert.ToBoolean(dReader[32]);
int pren = Convert.ToInt32(dReader[33]);
int betalare = Convert.ToInt32(dReader[34]);
int kredit = Convert.ToInt32(dReader[35]);
int fornyanr = Convert.ToInt32(dReader[36]);
string landskod = Convert.ToString(dReader[37]);
DateTime? nästsist = null;
try
{
nästsist = Convert.ToDateTime(dReader[38]);
}
catch { }
string fax = Convert.ToString(dReader[39]);
string epost = Convert.ToString(dReader[40]);
string hemsida = Convert.ToString(dReader[41]);
string bic = Convert.ToString(dReader[42]);
string iban = Convert.ToString(dReader[43]);
string faktkoll = Convert.ToString(dReader[44]);
var tidning = new Tidning();
tidning.Id = id;
tidning.Namn = namn;
tidning.Datadir = datadir;
tidning.Adr1 = adr1;
tidning.Adr2 = adr2;
tidning.Regnr = regnr;
tidning.Tel = tel;
tidning.Pg = pg;
tidning.Bg = bg;
tidning.Villkor = villkor;
tidning.Sista_nr = sista_nr;
tidning.FaktAvg = faktavg;
tidning.Vilande = vilande;
tidning.Listlopnr = listlopnr;
tidning.Faktnr = faktnr;
tidning.Moms = moms;
tidning.AviPriskod = avipriskod;
tidning.InbetDatum = inbetdat;
tidning.Period = period;
tidning.AviTyp = (AviTyp)Enum.Parse(typeof(AviTyp), avityp, true);
tidning.SistAviDatum = sistavidat;
tidning.FromDatum = fromdatum;
tidning.TomDatum = tomdatum;
tidning.FromPrennr = fromprennr;
tidning.TomPrennr = tomprennr;
tidning.Databasversion = databasversion;
tidning.Nummerperiod = nummerperiod;
tidning.Nolastyear = nolastyear;
tidning.Nonextyear = nonextyear;
tidning.Dubbelnummer = dubbelnummer;
tidning.Skrivetik = skrivetik;
tidning.Utrmomsavdrag = utrmomsavdrag;
tidning.Buntning = buntning;
tidning.Pren = pren;
tidning.Betalare = betalare;
tidning.Kredit = kredit;
tidning.Fornyanr = fornyanr;
tidning.Landskod = landskod;
tidning.NastSist = nästsist;
tidning.Fax = fax;
tidning.Epost = epost;
tidning.Hemsida = hemsida;
tidning.Bic = bic;
tidning.Iban = iban;
tidning.Faktkoll = faktkoll;
tidningLista.Add(tidning);
}
} while (dReader.NextResult());
databas6.Tidnings.AddRange(tidningLista);
databas6.SaveChanges(); //<--- This is where it goes wrong
excelConnection.Close();
return ("hej"); //<--- Do not mind this one
}
}
}
If you need any further information, just tell me and I will provide it. The main thing I want is to get this working and this is not the only code giving me this problem, but if this one can be solved, then maybe the other ones can be solved the same way.
This error is caused when you are trying to add invalid data to your database table.
e.g. you are adding string of 100 chars to the table column but in table definition your column has maxlength of 50. in that case value you are adding is invalid as per the column definitions and this error occur.
you should log what properties are causing the error. for that you can use below code:
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
Logger.WriteError("{0}{1}Validation errors:{1}{2}", ex, Environment.NewLine, ex.EntityValidationErrors.Select(e => string.Join(Environment.NewLine, e.ValidationErrors.Select(v => string.Format("{0} - {1}", v.PropertyName, v.ErrorMessage)))));
throw;
}
You can catch these errors easily ,using the watch window, without writing much code.
Kindly find the very good solution in the following link
https://stackoverflow.com/a/40732784/3397630
I really inspired in the way that answer was given, with the very good screenshots . Sharing it here with the hope it will be helpful to you and the others.
thanks
KArthik

how to get history info from QC using OTA

Below My Code that gets info of Bug history from QC. I have problem with
AuditPropertyFactoryFilter which does not filter. AuditPropertyFactory has more than thousand rows.
If I comment
var changesList = auditPropertyFactory.NewList(changesHistoryFilter.Text); and uncomment
next line, auditPropertyFactory has several rows only but it isn't filtered as i need.
Can anyone get some advice?
public List<QCBugHistory> retrieveHistoryFromBug(string bugId)
{
List<QCBugHistory> history = new List<QCBugHistory>();
try
{
TDConnection qcConnection = new TDConnection();
qcConnection.InitConnectionEx(qcUrl);
qcConnection.ConnectProjectEx(qcDomain, qcProject, qcLogin);
if (qcConnection.Connected)
{
AuditRecordFactory auditFactory = qcConnection.AuditRecordFactory as AuditRecordFactory;
TDFilter historyFilter = auditFactory.Filter;
historyFilter["AU_ENTITY_TYPE"] = "BUG";
historyFilter["AU_ENTITY_ID"] = bugId;
historyFilter["AU_ACTION"] = "Update";
historyFilter.Order["AU_TIME"] = 1;
historyFilter.OrderDirection["AU_TIME"] = 1;
var auditRecordList = auditFactory.NewList(historyFilter.Text);
log.Info("кол-во в истории " + auditRecordList.Count);
if (auditRecordList.Count > 0)
{
foreach (AuditRecord audit in auditRecordList)
{
QCBugHistory bugHistory = new QCBugHistory();
bugHistory.actionType = audit["AU_ACTION"];
bugHistory.changeDate = audit["AU_TIME"];
AuditPropertyFactory auditPropertyFactory = audit.AuditPropertyFactory;
var changesHistoryFilter = auditPropertyFactory.Filter;
changesHistoryFilter["AP_PROPERTY_NAME"] = "Status";
var changesList = auditPropertyFactory.NewList(changesHistoryFilter.Text);
//var changesList = auditPropertyFactory.NewList("");
if (changesList.Count > 0)
{
foreach (AuditProperty prop in changesList)
{
//prop.EntityID
if (prop["AP_PROPERTY_NAME"] == "Status")
{
bugHistory.oldValue = prop["AP_OLD_VALUE"];
bugHistory.newValue = prop["AP_NEW_VALUE"];
history.Add(bugHistory);
}
}
}
}
}
}
}
catch (Exception e)
{
log.Error("Проблема соединения и получения данных из QC ", e);
}
return history;
}
Try this (in C#):
1) Having only BUG ID param (BUGID below):
BugFactory bgFact = TDCONNECTION.BugFactory;
TDFilter bgFilt = bgFact.Filter;
bgFilt["BG_BUG_ID"] = BUGID; // This is a STRING
List bugs = bgFilt.NewList();
Bug bug = bugs[1]; // is 1-based
bug.History;
2) Having the Bug object itself, just do:
bug.History;

Read facebook message box

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.

Categories

Resources