Heres my code:
public userScreen(string uName)
{
InitializeComponent();
userName = uName;
string topLogNumber = "0";
textBox2.Text = userName;
Conversion(topLogNumber);
textBox1.Text = topLogNumber;
this.WindowState = FormWindowState.Maximized;
private string Conversion(string lognumber)
{
lognumber = gettoplognumber();
int lognumberint = Convert.ToInt32(lognumber);
lognumberint = lognumberint+1;
lognumber = lognumberint.ToString();
return lognumber;
}
private string gettoplognumber()
{
string selectTopLogNumber = "SELECT MAX (LogNo) from Logs";
string connection = "Data Source = \"EventControl.sdf\"";
SqlCeConnection connexion = new SqlCeConnection(connection);
SqlCeCommand topLog = new SqlCeCommand(selectTopLogNumber, connexion);
try
{
connexion.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return "error";
}
return topLog.ExecuteScalar() as string;
Now, what this code does is look into a database and increments the number by one. When it runs through (I have debugged the whole process), for some reason its all fine, until it reaches textBox1.Text = topLogNumber; at which point it changes back to "". Anyone????
Change this line to get the result of Conversion
topLogNumber = Conversion(topLogNumber);
or just assign the result of Conversion to your textbox
textBox1.Text = Conversion(topLogNumber);
The result of the calculation inside Conversion is passed back in the return statement. You need to reassign the result of that calc to the variable topLogNumber used inside the userScreen.
Related
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
I faced a problem while trying to build a Windows form solution for a college assignment, and hope somebody can point out my mistake.
The solution is about a mobile shop. I have two classes, Apple and Android forms. I need to read the data in the database table, categorize the entries to either Android or Apple phones, and then display all phones in a list when the form loads.
I can successfully categorize phones, but when trying to read the entries, I always end up with the same entry twice in my list on the form, while the second entry doesn't appear at all.
I know I made a big stupid mistake while doing the connection but I can't find it!.
Here is my code:
public abstract class MobilePhone {
private Int32 phoneID;
private string operatingSystem;
private string make;
private string model;
public enum Condition { Poor, Fair, Good, Mint };
private Condition condition;
private decimal originalPrice;
private DateTime datePurchase;
private string description;
private clsDataConnection dbConnection;
//constructor
public MobilePhone(string make, string model, decimal originalPrice, DateTime datePurchase, Condition condition, string description) {
this.make = make;
this.model = model;
this.originalPrice = originalPrice;
this.datePurchase = datePurchase;
this.condition = condition;
this.description = description;
}
Not complete, but that's what is relevant:
public class ApplePhone : MobilePhone {
decimal ApproxValue;
public ApplePhone(string make, string model, decimal originalPrice, DateTime datePurchase, Condition condition, string description)
: base(make, model, originalPrice, datePurchase, condition, description) {
}
The Android class is the same but with different other functions.
class Shop {
clsDataConnection dbConnection;
const int NotAdded = -1; // invalid primary key
private string name;
private decimal ApproxValue;
private Int32 phoneID;
private string operatingSystem;
private string make;
private string model;
private MobilePhone.Condition condition;
private decimal originalPrice;
private DateTime datePurchase;
private string description;
Int32 Index;
private List<MobilePhone> phonesForSale;
//constructor
public Shop(string name) {
this.name = name;
}
MobilePhone phone;
public void SelectAll() {
dbConnection = new clsDataConnection();
dbConnection.Execute("SellectAllPhones");
}
public void FilterByOperatingSystem(string operatingSystem) {
dbConnection = new clsDataConnection();
dbConnection.AddParameter("#OperatingSystem", operatingSystem);
dbConnection.Execute("FilterByOperatingSystem");
}
public Int32 Count {
get {
//return the count of records
return dbConnection.Count;
}
}
public string DescribeCurrentPhone(int Index) {
Int32 phoneID;
string make;
string model;
MobilePhone.Condition condition;
decimal originalPrice;
DateTime datePurchase;
string description;
phoneID = Convert.ToInt32(phonesForSale[Index].PhoneID);
make = Convert.ToString(phonesForSale[Index].Make);
model = Convert.ToString(phonesForSale[Index].Model);
condition = phonesForSale[Index].GetCondition;
originalPrice = Convert.ToDecimal(phonesForSale[Index].OriginalPrice);
datePurchase = Convert.ToDateTime(phonesForSale[Index].DatePurchased);
description = Convert.ToString(phonesForSale[Index].Description);
//set up a new object of class list item
string listItemText = make + " " + "|" + " " + model + " " + "|" + " " + condition + " " + "|" + " " + "£" + Math.Round(originalPrice, 2) + " " + "|" + " " + datePurchase.ToShortDateString() + " " + "|" + " " + description;
return listItemText;
}
public List<MobilePhone> Allphones {
get {
phonesForSale = new List<MobilePhone>();
int count = Count;
Index = 0;
while (Index < count) {
phoneID = Convert.ToInt32(dbConnection.DataTable.Rows[Index]["PhoneId"]);
operatingSystem = Convert.ToString(dbConnection.DataTable.Rows[Index]["OperatingSystem"]);
make = Convert.ToString(dbConnection.DataTable.Rows[Index]["Make"]);
model = Convert.ToString(dbConnection.DataTable.Rows[Index]["Model"]);
string conditionString = Convert.ToString(dbConnection.DataTable.Rows[Index]["Condition"]);
originalPrice = Convert.ToInt32(dbConnection.DataTable.Rows[Index]["OriginalPrice"]);
datePurchase = Convert.ToDateTime(dbConnection.DataTable.Rows[Index]["DatePurchased"]);
description = Convert.ToString(dbConnection.DataTable.Rows[Index]["Description"]);
// Set Condition
if (conditionString == "Poor") {
condition = MobilePhone.Condition.Poor;
} else if (conditionString == "Fair") {
condition = MobilePhone.Condition.Fair;
} else if (conditionString == "Good") {
condition = MobilePhone.Condition.Good;
} else if (conditionString == "Mint") {
condition = MobilePhone.Condition.Mint;
}
//check Operating System
if (operatingSystem == "IOS") {
phone = new ApplePhone(make, model, originalPrice, datePurchase, condition, description);
//ApproxValue = ApplePhone.CalculateApproximateValue();
} else if (operatingSystem == "Android") {
phone = new AndroidPhone(make, model, originalPrice, datePurchase, condition, description);
//ApproxValue = AndroidPhone.CalculateApproximateValue();
}
Index++;
phonesForSale.Add(phone);
}
return phonesForSale;
}
}
And the form code is:
public partial class FormMain : Form {
public FormMain() {
InitializeComponent();
Shop shop = new Shop("");
}
private void FormMain_Load(object sender, EventArgs e) {
DisplayItems("");
}
protected int DisplayItems(string operatingSystem) {
Shop MyShop = new Shop("");
Int32 RecordCount;
Int32 Index = 0;
Int32 PID;
if (operatingSystem != "") {
MyShop.FilterByOperatingSystem(operatingSystem);
} else {
MyShop.SelectAll();
}
RecordCount = MyShop.Count;
ArrayList MyPhones = new ArrayList();
while (Index < RecordCount) {
// I Suspect this line is the problem but don't know how to fix it
PID = MyShop.Allphones[Index].PhoneID
string listItemText = MyShop.DescribeCurrentPhone(PID);
//add the new item to the list
MyPhones.Add(listItemText);
//increment the index
Index++;
}
listBox1.DataSource = MyPhones;
return RecordCount;
}
I am not used to connecting to databases, so any advice will be of help!
An example of an alternative to the DB connection you have made is below
List<MyPhone> myIPhoneList = new List<Myphone>();
List<MyPhone> myAndroidList = new List<Myphone>();
SqlConnection myDBConnection = new SqlConnection("MyConnectionString"); //DB Connection
SqlCommand dbCommand = new SqlCommand("SelectAllPhones"); //Stored Procedure
SqlDataReader recordReader = dbCommand.ExecuteReader(); //Execute
//Read records return in to phone objects
while (recordReader.Read()) {
var phoneField1 = recordReader["PhoneField1FromDatabase"];
var phoneField2 = recordReader["PhoneField2FromDatabase"];
//etc...
var myPhone = new MyPhone();
myPhone.Name = phoneField1;
//etc...
if (myPhone.OS == "iPhone")
myIPhoneList.Add(myPhone);
if (myPhone.OS = "Android")
myAndroidList.Add(myPhone);
}
Just a twist to Wheels answer really,
I'd personally put a filter on the stored-proc.
SqlCommand dbCommand = new SqlCommand("SelectAllPhones"); //Stored Procedure
becomes something like:
using (SqlConnection conn = new SqlConnection())
{
using (SqlCommand cmd = new SqlCommand("SelectAllPhones", conn))
{
cmd.Parameters.Add(new SqlParameter() { ParameterName = "#OS", SqlDbType = SqlDbType.VarChar, Direction = ParameterDirection.Input, Value = phoneOS });
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// load your data...
}
}
}
Only because there is very little point dragging both sets of phone data (android/iphone) for each class. You may as well only pull back the data you require.
Of course the Stored-Proc will need an update to cater for the parameter.
something like:
AND PhoneOS = #OS
needs appending to your SQL condition.
clsDataConnection dbConnection; is unknown to me - is this a third party library or a class you've wrote and not included?
public Int32 Count
{
get
{
//return the count of records
return dbConnection.Count;
}
}
dbConnection.Count seems very non-standard. Doesn't read as if you're trying to get the number of rows, more the number of connections - which is invalid here.
dbConnection.DataTables[0].Rows.Count; would be a better way of determining the rows using your existing code, as currently it reads as if your counting the number of database connections which isn't what your after - and would be redundant if using either mine or Wheels as you wont need to know beforehand how many rows your about to process.
I have a list box on my WinForms application which populates with the following SQL code in C#:
private void PopulateClients()
{
string sqlText = "SELECT ClientID, ClientName FROM tblClients;";
cSqlQuery cS = new cSqlQuery(sqlText, "table");
lbxClient.DataSource = cS.cTableResults;
lbxClient.DisplayMember = "ClientName";
lbxClient.ValueMember = "ClientID";
}
So whilst the list box displays client names, the value it should return when selected is the numerical clientID.
However, later in the code -
private void btnAddNewJob_Click(object sender, EventArgs e)
{
try
{
string strNewJobName = txtNewJobName.Text;
string strNewJobRef = txtNewJobRef.Text;
int intNewJobClient = (int)lbxClient.SelectedValue;
string sqlText = "INSERT INTO tblJobs (JobID, JobClient, JobRef, JobName) " +
"VALUES (#JobID, #JobClient, #JobRef, #JobName);";
SqlCommand sqlCom = new SqlCommand(sqlText);
sqlCom.Parameters.Add("#JobID", SqlDbType.Int);
sqlCom.Parameters.Add("#JobClient", SqlDbType.Int);
sqlCom.Parameters.Add("#JobRef", SqlDbType.Text);
sqlCom.Parameters.Add("#JobName", SqlDbType.Text);
cConnectionString cS = new cConnectionString();
sqlCom.Parameters["#JobID"].Value = cS.NextID("JobID", "tblJobs");
sqlCom.Parameters["#JobClient"].Value = intNewJobClient;
sqlCom.Parameters["#JobRef"].Value = strNewJobRef;
sqlCom.Parameters["#JobName"].Value = strNewJobName;
cSqlQuery cQ = new cSqlQuery(sqlCom, "non query");
PopulateJobs();
txtNewJobName.Text = "";
txtNewJobRef.Text = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Fails on the third line
int intNewJobClient = (int)lbxClient.SelectedValue;
With an invalid cast. As far as I can see the listbox is still returning the Client Name, whereas it should be returning then numerical clientID (int).
Any ideas?
Your code should work - just tested that.
Make sure that the data you are binding to is correct - especially ClientID
also make sure that the value is selected before casting to int
Hope it helps
lbxClient.SelectedValue is a string. It should be converted to an int like so:
int intNewJobClient = Convert.ToInt32(lbxClient.SelectedValue);
Hope this helps.
In the end I had to do this:
int intClient = 0;
try
{
intClient = (int)lbxClient.SelectedValue;
}
catch (Exception)
{
intClient = 0;
}
Which I feel like is a bit of a fudge - but it works!
You code should work, However you should place a sanity check on the SelectedValue on the index.
if (lbxClient.SelectedIndex != -1)
{
int intClient = 0;
try
{
intClient = Convert.ToInt32(lbxClient.SelectedValue);
}
catch (Exception)
{
// catch if the value isn't integer.
intClient = -1;
}
}
I had the same problem but its resolved now by doing this
Replace this
lbxClient.DataSource = cS.cTableResults;
lbxClient.DisplayMember = "ClientName";
lbxClient.ValueMember = "ClientID";
With
lbxClient.DisplayMember = "ClientName";
lbxClient.ValueMember = "ClientID";
lbxClient.DataSource = cS.cTableResults;
Just place the first line "DataSource=" in last and the you will get rid out of it :)
The reason is doing this explained in #Sebastian answer.
Background:
I am trying to add data to a SQL DB with C#. I am currently doing so in my script in another class so im using the same code (the code works). However, my current class is using a bunch of recycled code and i am having issues narrowing down why i can not write to the DB. Below is the code i am using and it is broken down to the bare bones minimum code.
What I'm asking for:
anyone to point out some dumb mistake i made or ideas where to troubleshoot. Currently i am just staring at this code and cant see whats wrong.
Thanks in advance!
public void AddAttachmentToDB(XmlNode root, XmlNamespaceManager xmlns, string MessageID, string MailBoxAliasName)
{
//open DB
#region Open DB
if (DbConnection.State != System.Data.ConnectionState.Open)
{
try
{
this.DbConnection.ConnectionString = DbConnectionString;
this.DbConnection.Open();
MailboxListener._logging.LogWrite("[{0}] opened DB Connection in AddAttachmentToDB!",
LoggingLevels.Error,
System.Reflection.MethodBase.GetCurrentMethod().ToString(),
this.DbConnectionString);
}
catch (Exception ex)
{
MailboxListener._logging.LogWrite("[{0}] Failed to open DB Connection! For Machine: {1}",
LoggingLevels.Error,
System.Reflection.MethodBase.GetCurrentMethod().ToString(),
this.DbConnectionString);
MailboxListener._logging.LogWrite("[{0}] Error Returned: {1}",
LoggingLevels.Error,
System.Reflection.MethodBase.GetCurrentMethod().ToString(),
ex.Message.ToString());
}
}
else
{
MailboxListener._logging.LogWrite("[{0}] Failed to open DB Connection in AddAttachmentToDB!",
LoggingLevels.Error,
System.Reflection.MethodBase.GetCurrentMethod().ToString(),
this.DbConnectionString);
}
#endregion
//once db is open try this
try
{
//create test variables
string strMailBoxAliasName = MailBoxAliasName;
string AttachmentFilename = string.Empty;
string strfiletype = string.Empty;
string AttachmentStream = string.Empty;
string strAttachmentID = string.Empty;
string strMessageID = string.Empty;
strMessageID = MessageID;
//fill test variables
AttachmentFilename = "yumyum";
AttachmentStream = "Cheetos";
strMessageID = "123";
strMailBoxAliasName = "user";
strfiletype = ".txt";
strAttachmentID = "12345";
//create sql insert string
String insString = #"INSERT INTO MailboxListenerAttachments Values (#attachmentfilename, #attachmentbody,
#messageID, #mailboxname, #filetype, #attachmentID, #DateAddedToDB)";
//create sql command string
SqlCommand myCommand = new SqlCommand(insString, this.DbConnection);
//add fill test variables to sql insert string
myCommand.Parameters.Add("#attachmentfilename", SqlDbType.VarChar, 100);
myCommand.Parameters["#attachmentfilename"].Value = AttachmentFilename;
myCommand.Parameters.Add("#attachmentbody", SqlDbType.VarChar, 8000);
myCommand.Parameters["#attachmentbody"].Value = AttachmentStream.Trim();
myCommand.Parameters.Add("#messageID", SqlDbType.VarChar, 500);
myCommand.Parameters["#messageID"].Value = strMessageID;
myCommand.Parameters.Add("#mailboxname", SqlDbType.VarChar, 100);
myCommand.Parameters["#mailboxname"].Value = strMailBoxAliasName;
myCommand.Parameters.Add("#filetype", SqlDbType.VarChar, 50);
myCommand.Parameters["#filetype"].Value = strfiletype;
myCommand.Parameters.Add("#attachmentID", SqlDbType.VarChar, 50);
myCommand.Parameters["#attachmentID"].Value = strAttachmentID;
myCommand.Parameters.Add("#DateAddedToDB", SqlDbType.DateTime);
myCommand.Parameters["#DateAddedToDB"].Value = DateTime.UtcNow.ToString();
//run sql command
myCommand.ExecuteNonQuery();
//log sql command events
MailboxListener._logging.LogWrite(
"[{0}] Added attachment {1} to database for messageID: {2}",
LoggingLevels.Informational,
System.Reflection.MethodBase.GetCurrentMethod().ToString(),
AttachmentFilename,
strMessageID
);
//if DB is open, close it
if (DbConnection.State == System.Data.ConnectionState.Open)
{
this.DbConnection.Close();
}
}
//catch errors
catch (Exception ex)
{
MailboxListener._logging.LogWrite("[{0}] Error Returned: {1}",
LoggingLevels.Error,
System.Reflection.MethodBase.GetCurrentMethod().ToString(),
ex.Message.ToString());
}
}
No idea why this doesn't work but this code screams for refactoring:
public void AddAttachmentToDB(
XmlNode root,
XmlNamespaceManager xmlns,
string MessageID,
string MailBoxAliasName
)
{
var strMailBoxAliasName = MailBoxAliasName;
var AttachmentFilename = "yumyum";
var AttachmentStream = "Cheetos";
var strMessageID = "123";
var strMailBoxAliasName = "user";
var strfiletype = ".txt";
var strAttachmentID = "12345";
// Use DateTime when working with dates
var dates123 = new DateTime(2011, 2, 3);
try
{
using (var conn = new SqlConnection(DbConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = #"INSERT INTO MailboxListenerAttachments Values (#attachmentfilename, #attachmentbody, #messageID, #mailboxname, #filetype, #attachmentID, #DateAddedToDB";
cmd.Parameters.AddWithValue("#attachmentfilename", AttachmentFilename);
cmd.Parameters.AddWithValue("#attachmentbody", AttachmentStream.Trim());
cmd.Parameters.AddWithValue("#messageID", strMessageID);
cmd.Parameters.AddWithValue("#mailboxname", strMailBoxAliasName);
cmd.Parameters.AddWithValue("#filetype", strfiletype);
cmd.Parameters.AddWithValue("#attachmentID", strAttachmentID);
cmd.Parameters.AddWithValue("#DateAddedToDB", dates123);
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
// TODO: Log the exception and propagate it
throw ex;
}
}
Shouldn't Dates123 be of a DateTime type instead of a string?
I think you need to specify input/output directions for all of the paramters.
for example : myCommand.Parameters["#attachmentfilename"].Direction = ParameterDirection.Input
If you really have no idea you can try
Fix your insert statement so it
explicitly names columns maybe your
ordering is incorrect and insert
statement doesnt work
your setting parameters length to
maximum column length values, maybe you
need to set them to actual parameter
values length
I really think that Dates123 is
indeed the most important problem here, it
should be DateTime not string.
So you changed it but you still call DateTime.UtcNow.ToString() , leave it as DateTime type not string.
Here is the update query which i am using to update a table. It throws me an exception "Incorrect Syntax near Where" Why is that exception for? i have no idea.
public bool UpdateLocationCountintoMerchantPackage(int PackageID, long MerchantID,int LocationCount)
{
try
{
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter("#packageID",PackageID),
new SqlParameter("#merchantID",MerchantID ),
new SqlParameter("#locationCount",LocationCount )
};
string CommandText = string.Empty;
CommandText = "Update Merchant_Package SET LocationCount Where MerchantID=#MerchantID";
string ConnectionString = DbConnectionStrings.GetDbConnectionString();
SqlHelper.ExecuteNonQuery(ConnectionString, System.Data.CommandType.Text, CommandText, parameters);
return true;
}
catch (SqlException ex)
{
LogError("Error Occurred When Saving Merchant Location Count Data : MerchantID:" + MerchantID.ToString(), ex);
return false;
}
}
this function is called from
protected void imgbtnSubmit_Click(object sender, ImageClickEventArgs e)
{
UpdatePaymentInfo();
string QueryString = Request.QueryString.ToString();
if (string.Equals(QueryString, "MerchantProfilePages"))
{
Response.Redirect(ApplicationData.URL_ADD_PROFILE_PAGE, false);
Merchant mrchnt = new Merchant();
int PackId = mrchnt.PackageID;
int x = GetLocationCount() + 1;
mrchnt.UpdateLocationCountintoMerchantPackage(PackId, merchantId, x);
}
It's an issue with your "SET LocationCount" - you're not setting it equal to anything. That's why it's complaining about the WHERE.
Use SQL like:
Update Merchant_Package SET LocationCount=#LocationCount
Where MerchantID=#MerchantID
Your error on the 1st line was reported when WHERE was encountered