Magento add a product via SOAP from C# application - c#

I am trying to develop an application to insert a product using C# into Magento.
I have the code for connecting in here working:
http://www.magentocommerce.com/wiki/5_-_modules_and_development/web_services/using_soap_api_in_c_sharp
but I am new to c# and could do with a really simple example of how I go about adding a product, the API code for doing this in PHP is here:
http://www.magentocommerce.com/wiki/doc/webservices-api/api/catalog_product#example_2._product_createviewupdatedelete
Any help greatly appreciated.
John

MagentoService mservice = new MagentoService();
String mlogin = mservice.login("YOUR_USERNAME", "YOUR_API_KEY");
Debug.WriteLine(mlogin);
String productType = "simple";
String attributeSetId = "4"; // This is the ID of the Catalog Product Attribute Set
String productSku = "PRODUCT_SKU";
catalogProductCreateEntity[] cpce = new catalogProductCreateEntity[1];
// Some Code blocks here will follow....
catalogProductCreate[] cpc = mservice.catalogProductCreate(mlogin, productType, attributeSetId, productSku, cpce);
This is how it will work. But since I'm not a dotNet / C# developer, so I'll not be able to help you any further.
Hope it helps.

Here goes a simple product working sample..
First add the service reference to your project.
http://yourdomain.com/index.php/api/v2_soap/?wsdl
Then add some code...
static Mage_Api_Model_Server_Wsi_HandlerPortTypeClient mservice;
mservice = new Mage_Api_Model_Server_Wsi_HandlerPortTypeClient();
mlogin = mservice.login("username", "apikey");
catalogProductCreateEntity newProduct = new catalogProductCreateEntity();
newProduct.name = prodName;
newProduct.description = prodDesc;
newProduct.short_description = prodShort;
newProduct.status = "1";
newProduct.price = prodPrice;
newProduct.tax_class_id = "2";
try
{
mservice.catalogProductCreate(mlogin, "simple", "4", prodSku, newProduct, null);
}
catch (Exception merror)
{
lastError = merror.Message;
}
Something along those lines.... and some extra
static bool createCustomer(string dob, string email, string firstname, string lastname, string middlename, string prefix)
{
customerCustomerEntityToCreate newCustomer = new customerCustomerEntityToCreate();
newCustomer.dob = dob;
newCustomer.email = email;
newCustomer.firstname = firstname;
newCustomer.gender = 0;
newCustomer.genderSpecified = false;
newCustomer.lastname = lastname;
newCustomer.middlename = middlename;
newCustomer.password = "P#55w0rd!";
newCustomer.prefix = prefix;
newCustomer.suffix = "";
newCustomer.taxvat = "";
newCustomer.website_id = 1;
newCustomer.store_idSpecified = true;
newCustomer.group_id = 1;
newCustomer.store_id = 1;
try
{
mservice.customerCustomerCreate(mlogin, newCustomer);
}
catch (Exception merror)
{
lastError = merror.Message;
return false;
}
return true;
}
static bool updateCustomer(string dob, string email, string firstname, string lastname, string middlename, string prefix, int id)
{
customerCustomerEntityToCreate newCustomer = new customerCustomerEntityToCreate();
newCustomer.dob = dob;
newCustomer.email = email;
newCustomer.firstname = firstname;
newCustomer.gender = 0;
newCustomer.genderSpecified = false;
newCustomer.lastname = lastname;
newCustomer.middlename = middlename;
newCustomer.password = "P#55w0rd!";
newCustomer.prefix = prefix;
newCustomer.suffix = "";
newCustomer.taxvat = "";
newCustomer.store_idSpecified = true;
newCustomer.website_id = 2;
newCustomer.group_id = 2;
newCustomer.store_id = 2;
try
{
mservice.customerCustomerUpdate(mlogin,id, newCustomer);
}
catch (Exception merror)
{
lastError = merror.Message;
return false;
}
return true;
}
static void GetOrders(string dob, string email, string firstname, string lastname, string middlename, string prefix, int id)
{
filters mf = new filters();
complexFilter[] cpf = new complexFilter[1];
complexFilter mcpf = new complexFilter();
mcpf.key = "increment_id";
associativeEntity mas = new associativeEntity();
mas.key = "gt";
mas.value = "1";
mcpf.value = mas;
cpf[0] = mcpf;
mf.complex_filter = cpf;
salesOrderListEntity[] soe = mservice.salesOrderList(mlogin, mf);
if (soe.Length > 0)
{
foreach (salesOrderListEntity msoe in soe)
{
try
{
Console.WriteLine("" + msoe.billing_firstname + " " + msoe.subtotal);
}
catch (Exception merror)
{
Console.WriteLine("" + msoe.order_id + "" + merror.ToString());
}
}
}
}
HTH someone

Related

NullReferenceException When Using VerifyHashedPassword in asp.net core

Here's what happen i am working on login controller where i need to verify user input password with password hash that is in the database. When i'm trying to verify the correct password it is returning NullReferenceException: Object reference not set to an instance of an object. But when i debug it, the line with this code :
var verified = hasher.VerifyHashedPassword(inputModel, resultData.passwordhash, password);
is skipped and does not executed but when i return the value of verified.toString() directly after calling above line of code, it is printing a "Success" string. But when it is failed to verify, the code just work properly. Here's the full code :
public dbSearchResponse dbSearch(string username, string password, ADResponse ldapResult)
{
LoginResponse finalResult = new LoginResponse();
TableSystemUser resultData = new TableSystemUser();
PasswordHasher<OldLoginParamModel> hasher = new PasswordHasher<OldLoginParamModel>(
new OptionsWrapper<PasswordHasherOptions>(
new PasswordHasherOptions()
{
CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV2
}));
OldLoginParamModel inputModel = new OldLoginParamModel();
inputModel.grant_type = "password";
inputModel.password = password;
inputModel.username = username;
string hashedPassword = hasher.HashPassword(inputModel, inputModel.password);
using (var connection = new NpgsqlConnection(configuration.GetValue<string>("dbServer:connectionData")))
{
connection.Open();
try
{
var value = connection.Query<TableSystemUser>(
"SELECT id, email, emailconfirmed, passwordhash, phonenumber, username, fullname, dateofbirth, gender, COALESCE(usercredit.saldo, 0) as saldo, pricing.psc, pricing.psm, pricing.plc, pricing.plm, pricing.csc, pricing.csm, pricing.clc, pricing.clm, pricing.ssc, pricing.ssm, pricing.slc, pricing.slm FROM systemuser LEFT OUTER JOIN usercredit ON systemuser.id = usercredit.systemuserid INNER JOIN userpricing ON UUID(systemuser.id) = userpricing.systemuserid INNER JOIN pricing ON userpricing.pricingid = pricing.pricingid WHERE systemuser.email= '" + username + "' and systemuser.emailconfirmed = true;"
);
resultData = value.First();
}
catch (Exception e)
{
//Failed response
dbSearchResponse dbRespNRErr = new dbSearchResponse();
dbRespNRErr.loginResponse = null;
dbRespNRErr.userid = null;
dbRespNRErr.response = "Email not registered.";
return dbRespNRErr;
}
}
var verified = hasher.VerifyHashedPassword(inputModel, resultData.passwordhash, password);
/*But when return the verified.toString() value here, it is returning "Success"
dbSearchResponse dbRespErr = new dbSearchResponse();
dbRespErr.loginResponse = null;
dbRespErr.userid = null;
dbRespErr.response = verified.toString();
return dbRespErr; */
if (verified.toString() == "Success")
{
finalResult.FullName = resultData.fullname;
finalResult.Gender = resultData.gender;
//11/26/1998 12:00:00 AM
finalResult.DateOfBirth = resultData.dateofbirth.ToString("MM/dd/yyyy HH:mm:ss tt");
finalResult.Phone = resultData.phonenumber;
finalResult.Email = resultData.email;
finalResult.UserName = resultData.username;
finalResult.PLC = resultData.plc.ToString();
finalResult.PLM = resultData.plm.ToString();
finalResult.PSC = resultData.psc.ToString();
finalResult.PSM = resultData.psm.ToString();
finalResult.SLC = resultData.slc.ToString();
finalResult.SLM = resultData.slm.ToString();
finalResult.SSC = resultData.ssc.ToString();
finalResult.SSM = resultData.ssm.ToString();
finalResult.CLC = resultData.clc.ToString();
finalResult.CLM = resultData.clm.ToString();
finalResult.CSC = resultData.csc.ToString();
finalResult.CSM = resultData.csm.ToString();
finalResult.PayLater = ldapResult.memberof;
finalResult.Credit = resultData.saldo.ToString();
dbSearchResponse dbResp = new dbSearchResponse();
dbResp.loginResponse = finalResult;
dbResp.userid = resultData.id;
dbResp.response = "success";
return dbResp;
}
//Failed response
dbSearchResponse dbRespErr = new dbSearchResponse();
dbRespErr.loginResponse = null;
dbRespErr.userid = null;
dbRespErr.response = "The user name or password is incorrect.";
return dbRespErr;
}
Anyone know what happen and how to solve it? Thanks
After i do some detailed run check, i notice that the null part of the code is,
finalResult.PayLater = ldapResult.memberof;
But i don't understand why is the error response given suggest that the null was this line of code
var verified = hasher.VerifyHashedPassword(inputModel, resultData.passwordhash, password);
so in that case, i thanks to everyone who have responded to my question.

Async and await tasks are getting missed

I'm getting a "Because this call is not awaited..." on
SendPostAsync(CustomerName, email, Phone, maxImages, MainEventName, MainEventCode, CLemail, package_type, PlayerInfo, template_ID, favoritesArray);
Here's the button click:
private void btnCopyAllInvoices_Click(object sender, EventArgs e)
{
//sets up a list to store the incoming invoice numbers from the DB
List<string> InvoiceNums = new List<string>();
mySqlInterface.Connect();
InvoiceNums = mySqlInterface.GetNewInvoices();
//prep the visuals
lblStatus.Text = "";
InvoicePanel.Visible = true;
progressBarInvoice.Value = 0;
progressBarInvoice.Maximum = InvoiceNums.Count;
//for each invoice collected let's copy it
InvoiceNums.ForEach(delegate(string inv)
{
if (OrderDAL.CheckOrderExist(inv))
{
// the order already exist
Order myorder = new Order();
myorder = OrderDAL.GetOrder(inv);
CopyImages(myorder, true);
OrderDAL.UpdateFulfillment(string.Format("Images Copied"), inv);
}
});
//let the user know how we did
MessageBoxButtons buttons = MessageBoxButtons.OK;
string strError = string.Format("{0} Invoices copied.", InvoiceNums.Count);
MessageBox.Show(this, strError, "Copy New Invoices", buttons, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
InvoicePanel.Visible = false;
}
Here, CopyImages is called as part of the foreach loop above.
public void CopyImages(Order order, bool CopyAllInv)
{
string baseTarget = WorkSpace.Text;
string CLhotfolderTarget = string.Empty;
//check to see if the order has been photo released. If it has add "pr" to the end of the invoice number
string prInvoice = "";
if (order.Header.SignatureLine != "null" && order.Header.SignatureChecks != "null")
{
prInvoice = "pr";
}
string PackageName = null;
string CustomerName = null;
string Phone = null;
string email = null;
string PlayerInfo = null;
string PlayerName = null;
string PlayerNumber = null;
string MainEventName = null;
string MainEventCode = null;
string CLemail = null;
//go to the DB and get the info
mySqlInterface.Connect();
bool videoPackage = mySqlInterface.VideoInfo(order.Header.InvoiceNumber, out PackageName, out CustomerName, out Phone, out email, out PlayerName, out PlayerNumber, out MainEventName, out MainEventCode);
mySqlInterface.Close();
if (videoPackage)
{
if (PackageName.Contains("Video") || PackageName.Contains("Ultimate Ripken"))
{
CLemail = MainEventCode + "_" + email.Replace("#", "_").Replace(".", "_").Replace("+", "_");
PlayerInfo = PlayerName + " " + PlayerNumber;
int template_ID = 0;
if (txtCLtemplateID.Text != "")
{
template_ID = Convert.ToInt32(txtCLtemplateID.Text);
}
//we will always need a hotfolder. So let's set and create it now
CLhotfolderTarget = txtCLhotfolder.Text + "\\toUpload\\" + CLemail;
if (!System.IO.Directory.Exists(CLhotfolderTarget))
{
// create the directory
System.IO.Directory.CreateDirectory(CLhotfolderTarget);
}
int maxImages = 7;
int package_type = 2;
string[] favoritesArray = new string[maxImages];
//populate the array of images for the video
int count = 0;
foreach (Order.InvoiceImages image in order.ImageList)
{
favoritesArray[count] = image.ImageName;
count++;
}
//let's call the API and send info to CL
SendPostAsync(CustomerName, email, Phone, maxImages, MainEventName, MainEventCode, CLemail, package_type, PlayerInfo, template_ID, favoritesArray);
}
}
}
public async Task SendPostAsync(string name, string email, string phone, int photo_count, string event_name, string event_id, string dir_name, int package_type, string video_text, int template_id, string[] favoritesArray)
{
string postURL = null;
string token = null;
int delivery_method = 2;
//production
postURL = "https://search.apicall.com/photographer/customer";
token = "token xxxxxxxxxxxxxxxxxxxxx";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(postURL);
client.DefaultRequestHeaders.Add("Authorization", token);
string POSTcall = JsonConvert.SerializeObject(new { name, email, phone, photo_count, event_id, event_name, dir_name, package_type, video_text, delivery_method, template_id, favorites = favoritesArray });
//Send string to log file for debug
WriteLog(POSTcall);
StringContent stringContent = new StringContent(POSTcall, UnicodeEncoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(new Uri(postURL), stringContent);
string POSTresponse = await response.Content.ReadAsStringAsync();
WriteLog(POSTresponse);
//simplified output for debug
if (POSTresponse.Contains("error") && POSTresponse.Contains("false"))
{
lblStatus.Text = "Error Sending to CL";
}
else
{
lblStatus.Text = "Successfully added to CL";
}
}
I have an await on the HttpResponseMessage response = await client.PostAsync
If I run this one at a time, it works. But when I run this through a loop and there are a bunch back to back, I think the PostAsyncs are getting stepped on. I'm missing entires in the WriteLog.
It seems I need to do the async/awaits further upstream, right? This way I can run the whole method.
Referencing Async/Await - Best Practices in Asynchronous Programming, event handlers allow async void so refactor the code to be async all the way through.
refactor CopyImages to await the posting of the data
public async Task CopyImages(Order order, bool CopyAllInv) {
//...omitted for brevity
if (videoPackage) {
if (PackageName.Contains("Video") || PackageName.Contains("Ultimate Ripken")) {
//...omitted for brevity
await SendPostAsync(CustomerName, email, Phone, maxImages, MainEventName, MainEventCode, CLemail, package_type, PlayerInfo, template_ID, favoritesArray);
}
}
}
And update the event handler
private async void btnCopyAllInvoices_Click(object sender, EventArgs e) {
//sets up a list to store the incoming invoice numbers from the DB
List<string> InvoiceNums = new List<string>();
mySqlInterface.Connect();
InvoiceNums = mySqlInterface.GetNewInvoices();
//prep the visuals
lblStatus.Text = "";
InvoicePanel.Visible = true;
progressBarInvoice.Value = 0;
progressBarInvoice.Maximum = InvoiceNums.Count;
//for each invoice collected let's copy it
foreach(string inv in InvoiceNums) {
if (OrderDAL.CheckOrderExist(inv)) {
// the order already exist
Order myorder = OrderDAL.GetOrder(inv);
await CopyImages(myorder, true);
OrderDAL.UpdateFulfillment(string.Format("Images Copied"), inv);
}
}
//let the user know how we did
MessageBoxButtons buttons = MessageBoxButtons.OK;
string strError = string.Format("{0} Invoices copied.", InvoiceNums.Count);
MessageBox.Show(this, strError, "Copy New Invoices", buttons, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
InvoicePanel.Visible = false;
}
I would also advise against creating a HttpClient for each post request. Extract that out and use a single client.
static Lazy<HttpClient> httpClient = new Lazy<HttpClient>(() => {
var postURL = "https://search.apicall.com/photographer/customer";
var token = "token xxxxxxxxxxxxxxxxxxxxx";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(postURL);
client.DefaultRequestHeaders.Add("Authorization", token);
return client
});
public async Task SendPostAsync(string name, string email, string phone, int photo_count, string event_name, string event_id, string dir_name, int package_type, string video_text, int template_id, string[] favoritesArray)
{
var postURL = "https://search.apicall.com/photographer/customer";
int delivery_method = 2;
string POSTcall = JsonConvert.SerializeObject(new { name, email, phone, photo_count, event_id, event_name, dir_name, package_type, video_text, delivery_method, template_id, favorites = favoritesArray });
//Send string to log file for debug
WriteLog(POSTcall);
StringContent stringContent = new StringContent(POSTcall, UnicodeEncoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.Value.PostAsync(new Uri(postURL), stringContent);
string POSTresponse = await response.Content.ReadAsStringAsync();
WriteLog(POSTresponse);
//simplified output for debug
if (POSTresponse.Contains("error") && POSTresponse.Contains("false")) {
lblStatus.Text = "Error Sending to CL";
} else {
lblStatus.Text = "Successfully added to CL";
}
}

How to link a module in asp.net, C# web application in all forms

Is there a way for me to link my module in all of my form i'm using c# app and this is my code. This is actually a notification bell that will notify users if he/she has/have notifications. I already linked it on homepage how am i able to do that in all other pages
private void systemNotificationREXS(HomePage module)
{
TextBox Username = (TextBox)module.FindControl("Hide_user");
Label Fullname = (Label)module.FindControl("userfullname");
Label notifLabel = (Label)module.FindControl("notifLabel");
using (con = new SqlConnection(EXCUSESLPCON))
{
using (cmd = new SqlCommand("SYSTEMNOTIFICATIONEXSLIP", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#userfullname", Fullname.Text);
con.Open();
using(adp = new SqlDataAdapter(cmd))
{
using(dt = new DataTable())
{
adp.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++ )
{
int notifcount = int.Parse(dt.Rows[i]["notifcount"].ToString());
string modulename = dt.Rows[i]["modulename"].ToString();
string modulebody = modulename + "Body";
string moduleLabel = modulename + "Label";
Label namebox = (Label)module.FindControl(modulename);
if (notifcount > 0)
{
namebox.Visible = true;
namebox.Text = notifcount.ToString();
module.FindControl(modulebody).Visible = true;
try
{
module.FindControl(moduleLabel).Visible = true;
}
catch
{
notifLabel.Visible = false;
}
}
else
{
namebox.Visible = false;
module.FindControl(modulebody).Visible = false;
try
{
module.FindControl(moduleLabel).Visible = false;
}
catch
{
notifLabel.Visible = false;
}
}
}
}
}
con.Close();
}
}
}
internal void notificationSystemREXS(string fullname, string hide_user, HomePage modulename)
{
systemNotificationREXS(modulename);
}
Code to linked on homepage:
private void systemNotificationREXS()
{
Notification moduleacc = new Notification();
moduleacc.notificationSystemREXS(userfullname.Text, Hide_user.Text, this);
}
Your method does very simple job, but you have made it complicated and over dependent on the module and other stuff.
The method should return only the notification data for the user and let the caller of the method to decide what to do with the data.
Consider doing following.
public class NotificationData
{
public int NotificationCount {get;set;}
public int ModuleName {get;set;}
}
public class NotificationService
{
public static List<NotificationData> GetNotificationData(string username)
{
var notificationList = new List<NotificationData>();
using (con = new SqlConnection(EXCUSESLPCON))
{
using (cmd = new SqlCommand("SYSTEMNOTIFICATIONEXSLIP", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#userfullname", Fullname.Text);
con.Open();
using(adp = new SqlDataAdapter(cmd))
{
using(dt = new DataTable())
{
for (int i = 0; i < dt.Rows.Count; i++ )
{
var notification = new NotificationData();
notification.NotificationCount = int.Parse(dt.Rows[i]["notifcount"].ToString());
notification.ModuleName = dt.Rows[i]["modulename"].ToString();
}
}
}
}
}
return notificationList
}
}
Now you should use this method from whichever page you want as following.
Let say you want to use it from HomePage. So you may write following code in Page_Load event of HomePage. (I am assuming here that HomePage is a web page and it has all the controls loaded before this code gets executed).
Label userNameLabel = (Label)this.FindControl("userfullname");
var userName = userNameLabelText;
var notificationList = NotificationService.GetNotificationData(userName);
foreach(var notification in notificationList)
{
var modulename = notification.ModuleName;
var notifcount = notification.Count;
string modulebody = modulename + "Body";
string moduleLabel = modulename + "Label";
Label namebox = (Label)this.FindControl(modulename);
if (notifcount > 0)
{
namebox.Visible = true;
namebox.Text = notifcount.ToString();
this.FindControl(modulebody).Visible = true;
try
{
this.FindControl(moduleLabel).Visible = true;
}
catch
{
notifLabel.Visible = false;
}
}
else
{
namebox.Visible = false;
this.FindControl(modulebody).Visible = false;
try
{
this.FindControl(moduleLabel).Visible = false;
}
catch
{
notifLabel.Visible = false;
}
}
}
I hope this should help you resolve your issue.

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

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