In my asp.net MVC application, There is an option to upload data from an excel file. For that, I have used this on my controller.
public ActionResult ImportEmpDetails(HttpPostedFileBase excelFile)
{
try
{
if (excelFile.ContentLength == 0 || excelFile == null)
{
ViewBag.Error = "Please select the excel file";
return View("EmpDetails");
}
else
{
if (excelFile.FileName.EndsWith("xls") || excelFile.FileName.EndsWith("xlsx"))
{
string path = Server.MapPath("~/ExcelFile/" + excelFile.FileName);
if (System.IO.File.Exists(path)) System.IO.File.Delete(path);
excelFile.SaveAs(path);
ExcelPath = Server.MapPath("~/ExcelFile/") + path;
Microsoft.Office.Interop.Excel.Application application = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook = application.Workbooks.Open(path);
Microsoft.Office.Interop.Excel.Worksheet worksheet = workbook.ActiveSheet;
Microsoft.Office.Interop.Excel.Range range = worksheet.UsedRange;
List<EmpDetailsVM> xcel = new List<EmpDetailsVM>();
for (int i = 2; i <= range.Rows.Count; i++)
{
try
{
EmpDetails emp = new EmpDetails();
int EmpNo = int.Parse(((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 1]).Text);
var EmpId = (from c in db.CreateEmployee where c.EmpNo == EmpNo select c.Id).First();
emp.EmpID = EmpId;
emp.YearOfService = decimal.Parse(((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 2]).Text);
emp.BasicSalary = decimal.Parse(((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 3]).Text);
emp.EmpCatagory = ((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 4]).Text;
emp.EmpGrade = ((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 5]).Text;
int SupervisorId = int.Parse(((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 6]).Text);
var SupId = (from h in db.CreateEmployee where h.EmpNo == SupervisorId select h.Id).First();
emp.SupervisorId = SupId;
EmpDetailsVM data = new EmpDetailsVM();
data.EmpID = emp.EmpID;
data.YearOfService = emp.YearOfService;
data.BasicSalary = emp.BasicSalary;
data.EmpCatagory = emp.EmpCatagory;
data.EmpGrade = emp.EmpGrade;
data.SupervisorId = emp.SupervisorId;
xcel.Add(data);
}
catch (Exception ex)
{
ViewBag.Error = "Error in " + i + " record";
return View("EmpDetails");
}
}
if (xcel != null)
{
try
{
foreach (var item in xcel)
{
int empID = item.EmpID;
decimal yearOfService = item.YearOfService;
decimal basicSalary = item.BasicSalary;
string catagory = item.EmpCatagory;
string grade = item.EmpGrade;
int supId = item.SupervisorId;
var isEmployeeExists = (from e in dbs.EmpDetails where e.EmpID == empID select e.Id).ToList();
int EmpCount = isEmployeeExists.Count();
if (EmpCount == 0)
{
EmpDetails e = new EmpDetails();
e.EmpID = empID;
e.YearOfService = yearOfService;
e.BasicSalary = basicSalary;
e.EmpCatagory = catagory;
e.EmpGrade = grade;
e.SupervisorId = supId;
dbs.EmpDetails.Add(e);
dbs.SaveChanges();
}
else
{
EmpDetails EmpDetails = dbs.EmpDetails.Where(x => x.EmpID == empID).First();
EmpDetails.YearOfService = yearOfService;
EmpDetails.BasicSalary = basicSalary;
EmpDetails.EmpCatagory = catagory;
EmpDetails.EmpGrade = grade;
EmpDetails.SupervisorId = supId;
db.SaveChanges();
}
}
}
catch (Exception ex)
{
ViewBag.Error = "Error " + ex;
}
TempData["msg"] = "success";
return View("EmpDetails", xcel);
}
else
{
}
return View("EmpDetails");
}
else
{
ViewBag.Error = "Selected excel file not supported";
return View("EmpDetails");
}
}
}
catch (Exception ex)
{
string message = string.Format("<b>Message:</b> {0}<br /><br />", "You do not have access to this view");
message += string.Format("<b>StackTrace:</b> {0}<br /><br />", ex.StackTrace.Replace(Environment.NewLine, string.Empty));
message += string.Format("<b>Source:</b> {0}<br /><br />", ex.Source.Replace(Environment.NewLine, string.Empty));
message += string.Format("<b>TargetSite:</b> {0}", ex.TargetSite.ToString().Replace(Environment.NewLine, string.Empty));
ModelState.AddModelError("Id", message);
}
return View("EmpDetails");
}
This is working properly when I debug the code and run from it using VS. When I applied to the live version, can't upload the excel file there is an exception triggering You do not have access to this view
Want to know how to prevent this or how to do same using stream ?
Related
I am doing Import page and if user leave some entry blank and click on import button I want to fill blank entries with Missing. I have tried that like this:
if (liveryEntry.Text == null)
{
liveryEntry.Text = "Missing";
}
if (registrationEntry.Text == null)
{
registrationEntry.Text = "Missing";
}
if (airportEntry == null)
{
airportEntry.Text = "Missing";
}
if (commentEntry == null)
{
commentEntry.Text = "Missing";
}
But sometimes it works and fill it with Missing, sometimes it doesnt work. What is wrong or is there another way to do that?
Here is full code of method:
private async void buttonImport_Clicked(object sender, EventArgs e)
{
var db = new SQLiteConnection(_dbPath);
db.CreateTable<Airplane>();
collectionPlane.IsVisible = false;
collectionAirline.IsVisible = false;
collectionLivery.IsVisible = false;
collectionRegistration.IsVisible = false;
collectionAirport.IsVisible = false;
try
{
if (liveryEntry.Text == null)
{
liveryEntry.Text = "Missing";
}
if (registrationEntry.Text == null)
{
registrationEntry.Text = "Missing";
}
if (airportEntry == null)
{
airportEntry.Text = "Missing";
}
if (commentEntry == null)
{
commentEntry.Text = "Missing";
}
if (planeEntry.Text != null && airlineEntry.Text != null)
{
var url = PhotoPick();
int i = 1;
int same = 0;
string fileName = registrationEntry.Text;
for (int b = 1; b <= GetNumberPhotos(); b++)
{
if (db.Table<Airplane>().FirstOrDefault(d => d.Id == b) != null)
{
var rowData = db.Table<Airplane>().FirstOrDefault(d => d.Id == b);
string match = rowData.Registration;
if (fileName == match)
{
same++;
}
}
}
i = 1 + same;
fileName = registrationEntry.Text + "-" + i;
var thumbUrl = CreateThumbnail(await url, fileName);
var maxPK = db.Table<Airplane>().OrderByDescending(c => c.Id).FirstOrDefault();
Airplane airplane = new Airplane()
{
Id = (maxPK == null ? 1 : maxPK.Id + 1),
SearchId = planeEntry.Text + airlineEntry.Text + liveryEntry.Text + registrationEntry.Text + airportEntry.Text + datePicker.Date.ToString() + commentEntry.Text,
Plane = planeEntry.Text.ToUpper(),
Airline = airlineEntry.Text,
Livery = liveryEntry.Text,
Registration = registrationEntry.Text.ToUpper(),
Airport = airportEntry.Text.ToUpper(),
Date = datePicker.Date,
Comment = commentEntry.Text,
Url = await url,
ThumbnailUrl = thumbUrl
};
db.Insert(airplane);
await DisplayAlert("Saved", planeEntry.Text + " of " + airlineEntry.Text + " is saved.", "OK");
planeEntry.Text = "";
airlineEntry.Text = "";
liveryEntry.Text = "";
registrationEntry.Text = "";
airportEntry.Text = "";
commentEntry.Text = "";
}
else
await DisplayAlert("Fill all needed fields", "You have to fill all fields except livery and comment", "OK");
}
catch
{
await DisplayAlert("Error", "Something went wrong", "Try again");
}
}
It is probably some kind of bug or missunderstanding #Cfun have solved with if ( string.IsNullOrEmpty(liveryEntry.Text)) and it works as expected.
People would like to ask you for help with the following situation.
I have a monitor where I check if certain machines are online. To make this process I have a script running on the machine feeding the database with the current time. Already on the monitor, I have an asynchronous check in Infinite loop to pick up the last updated time of the bank and update my Data Grid View. However I'm having some locking problems in this loop, someone could help follow my code
private void timer1_Tick(object sender, EventArgs e)
{
if (timerExec)
{
timerExec = false;
selectStatusRobos();
}
//timer1.Enabled = false;
}
public async void selectStatusRobos()
{
String Configuracao = "server=;user=midas_Client;password=;database=;port=3306";
string query = "SELECT i.Usuario_meta, i.Nome_robo, i.Simbolo, i.Periodo, i.Status_op, i.Operacao, i.Hora_criacao, c.Id, i.Corretora FROM int00 AS i INNER JOIN cliente00 AS c ON i.Usuario_meta = c.Usuario_meta AND i.Corretora = c.Corretora";
MySqlConnection conexao = new MySqlConnection(Configuracao);
try
{
await conexao.OpenAsync();
MySqlCommand COMANDO = new MySqlCommand(query, conexao);
MySqlDataAdapter adapter = new MySqlDataAdapter(COMANDO);
DataTable status = new DataTable();
await adapter.FillAsync(status);
bool flag_find = false;
for (int i = 0; i < dataGridView1.RowCount; i++)
{
flag_find = false;
dataGridView1.Rows[i].Cells["Status"].Value = Properties.Resources.if_exclamation_red_46014;
dataGridView1.Rows[i].Cells["Operacao"].Value = Properties.Resources.if_op_null;
dataGridView1.Rows[i].Cells["Status_op_img"].Value = Properties.Resources.if_op_null;
for (int b = 0; b < status.Rows.Count; b++)
{
if (dataGridView1.Rows[i].Cells["Id"].Value.ToString() == status.Rows[b]["Id"].ToString()
&& dataGridView1.Rows[i].Cells["Usuario_meta"].Value.ToString() == status.Rows[b]["Usuario_meta"].ToString()
&& dataGridView1.Rows[i].Cells["Corretora"].Value.ToString() == status.Rows[b]["Corretora"].ToString()
&& dataGridView1.Rows[i].Cells["Nome_robo"].Value.ToString() == status.Rows[b]["Nome_robo"].ToString()
&& dataGridView1.Rows[i].Cells["Simbolo"].Value.ToString() == status.Rows[b]["Simbolo"].ToString().Substring(0, 3)
&& dataGridView1.Rows[i].Cells["Periodo"].Value.ToString() == status.Rows[b]["Periodo"].ToString())
{
flag_find = true;
dataGridView1.Rows[i].Cells["Status"].Value = Properties.Resources.if_tick_circle_frame_27247;
dataGridView1.Rows[i].Cells["Hora_ultima"].Value = status.Rows[b]["Hora_criacao"].ToString();
if (status.Rows[b]["Operacao"].ToString() == "1") // Compra
{
dataGridView1.Rows[i].Cells["Operacao_img"].Value = Properties.Resources.if_Raise_32535_16;
dataGridView1.Rows[i].Cells["Operacao"].Value = status.Rows[b]["Operacao"].ToString();
}
else if (status.Rows[b]["Operacao"].ToString() == "2") // Venda
{
dataGridView1.Rows[i].Cells["Operacao_img"].Value = Properties.Resources.if_Fall_32468_16;
dataGridView1.Rows[i].Cells["Operacao"].Value = status.Rows[b]["Operacao"].ToString();
}
else
{
dataGridView1.Rows[i].Cells["Operacao_img"].Value = Properties.Resources.if_op_null;
dataGridView1.Rows[i].Cells["Operacao"].Value = status.Rows[b]["Operacao"].ToString();
}
if (status.Rows[b]["Status_op"].ToString() == "2") // Off
{
dataGridView1.Rows[i].Cells["Status_op_img"].Value = Properties.Resources.if_power_off_10214;
dataGridView1.Rows[i].Cells["Status_op"].Value = status.Rows[b]["Status_op"].ToString();
}
else if (status.Rows[b]["Status_op"].ToString() == "1") // On
{
dataGridView1.Rows[i].Cells["Status_op_img"].Value = Properties.Resources.if_power_on_10215;
dataGridView1.Rows[i].Cells["Status_op"].Value = status.Rows[b]["Status_op"].ToString();
}
dataGridView1.Rows[i].Cells["Status"].Value = Properties.Resources.if_tick_circle_frame_27247;
//query = "DELETE FROM `int00` WHERE Usuario_meta = #usuario_meta AND Nome_robo = #nome_robo AND Simbolo = #simbolo AND Periodo = #periodo";
//COMANDO.CommandText = query;
//COMANDO.Parameters.Clear();
//COMANDO.Parameters.Add("#usuario_meta", MySqlDbType.VarChar).Value = status.Rows[b]["Usuario_meta"].ToString();
//COMANDO.Parameters.Add("#nome_robo", MySqlDbType.VarChar).Value = status.Rows[b]["Nome_robo"].ToString();
//COMANDO.Parameters.Add("#simbolo", MySqlDbType.VarChar).Value = status.Rows[b]["Simbolo"].ToString();
//COMANDO.Parameters.Add("#periodo", MySqlDbType.VarChar).Value = status.Rows[b]["Periodo"].ToString();
//COMANDO.ExecuteNonQuery();
//break;
}
if (dataGridView1.Rows[i].Cells["Hora_ultima"].Value != null)
{
DateTime t = Convert.ToDateTime(dataGridView1.Rows[i].Cells["Hora_ultima"].Value.ToString());
// if (dataGridView1.Rows[i].Cells["Hora_ultima"].Value.ToString() != status.Rows[b]["Hora_criacao"].ToString())
if (flag_find)
{
DateTime t1 = DateTime.Now;
DateTime t2 = DateTime.Now.AddSeconds(-30);
System.TimeSpan diff2 = t1.Subtract(t);
if (diff2.TotalSeconds >= 15 && diff2.TotalSeconds <= 45)
{
dataGridView1.Rows[i].Cells["Status"].Value = Properties.Resources.if_58_62715;
}
else if (diff2.TotalSeconds < 15 && diff2.TotalSeconds >= 0)
{
dataGridView1.Rows[i].Cells["Status"].Value = Properties.Resources.if_tick_circle_frame_27247;
}
else
{
dataGridView1.Rows[i].Cells["Status"].Value = Properties.Resources.if_exclamation_red_46014;
}
}
}
}
}
//frm = this.MdiParent as frmPrincipal;
//SendMessage send = new SendMessage(frm.SetLabel);
//send(DateTime.Now.ToString("HH:mm :ss") + " - Dados Atualizados...", null, null);
conexao.Close();
}
catch (MySqlException ex)
{
frm = this.MdiParent as frmPrincipal;
SendMessage send = new SendMessage(frm.SetLabel);
send(DateTime.Now.ToString("HH:mm :ss") + " - Tempo limite excedido na seleção", ex.Message + ex.StackTrace, Properties.Resources.if_Close_Icon_Dark_1398917, 15000);
//MessageBox.Show(ex.Message + ex.StackTrace, "Detalhes Exception");
timerExec = true;
}
catch (TimeoutException ex)
{
frm = this.MdiParent as frmPrincipal;
SendMessage send = new SendMessage(frm.SetLabel);
send(DateTime.Now.ToString("HH:mm :ss") + " - Tempo limite excedido na seleção", ex.Message + ex.StackTrace, Properties.Resources.if_Close_Icon_Dark_1398917, 15000);
timerExec = true;
}
finally
{
frm = this.MdiParent as frmPrincipal;
SendMessage send = new SendMessage(frm.SetLabel);
send(DateTime.Now.ToString("HH:mm :ss") + " - Dados Atualizados...", null, null, 15000);
conexao.Close();
timerExec = true;
}
}
I got stuck when trying to implement the "apply credit" functionality of Quickbooks to existing invoices if credit is available for that customer. I am able to do it via Quickbooks Desktop UI but not getting the way to implement it via a .Net integrated app, written in C#. Can any one please guide on this.
Code which I am using to implement "apply credit" to Quickbooks via C# code.
I am getting the error: "QuickBooks found an error when parsing the provided XML text stream." with below code.
public void ApplyCreditsOnPrePayInvoices()
{
// open connection and begin session before data fetch - intentionally skipped this code
IMsgSetRequest msgset = null;
ICreditMemoQuery creditMemoQuery = null;
string sCustomerName = string.Empty;
if (this.GetConnectedToQB()) //this is the method call to login to quickbooks desktop
{
try
{
// during data fetch
msgset = m_sessionManager.CreateMsgSetRequest("US", 8, 0);
creditMemoQuery = msgset.AppendCreditMemoQueryRq();
creditMemoQuery.ORTxnQuery.TxnFilter.ORDateRangeFilter.ModifiedDateRangeFilter.FromModifiedDate.SetValue(new DateTime(2012, 3, 31), false);
IMsgSetResponse msgRes = m_sessionManager.DoRequests(msgset);
IResponseList responseList = msgRes.ResponseList;
if (responseList.Count > 0)
{
IResponse response = responseList.GetAt(0);
ICreditMemoRetList creditMemoList = response.Detail as ICreditMemoRetList;
if (creditMemoList == null)
{
return;
}
for (int i = 0; i <= creditMemoList.Count - 1; i++)
{
ICreditMemoRet qbCreditMemo = creditMemoList.GetAt(i);
if (this.GetQBCustomerListId(qbCreditMemo.CustomerRef.FullName.GetValue()) != string.Empty)
{
m_requestMsgSet.ClearRequests();
m_requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue;
IInvoiceAdd invoiceAddRq = m_requestMsgSet.AppendInvoiceAddRq();
invoiceAddRq.CustomerRef.FullName.SetValue(qbCreditMemo.CustomerRef.FullName.GetValue());
ISetCredit SetCredit1 = invoiceAddRq.SetCreditList.Append();
SetCredit1.CreditTxnID.SetValue(qbCreditMemo.TxnID.GetValue());
SetCredit1.AppliedAmount.SetValue(qbCreditMemo.TotalAmount.GetValue());
IMsgSetResponse responseSetInvoice = m_sessionManager.DoRequests(m_requestMsgSet);
DataSet dsInvoice = this.GetExtractResponseFromQB(responseSetInvoice);
string sQueryResponse = Stringcl.GetValue(dsInvoice.Tables["InvoiceAddRs"].Rows[0]["statusMessage"]);
if (sQueryResponse == "Status OK")
{
Console.WriteLine("Credit no.:" + qbCreditMemo.TxnID.GetValue() + " Customer:" + qbCreditMemo.CustomerRef.FullName.GetValue() + " Total:" + qbCreditMemo.TotalAmount.GetValue());
}
}
}
}
}
catch (Exception ex)
{
string ss = ex.Message;
//handle exception here
}
finally
{
if (msgset != null)
{
Marshal.FinalReleaseComObject(msgset);
}
if (creditMemoQuery != null)
{
Marshal.FinalReleaseComObject(creditMemoQuery);
}
}
}
// end session and close connection after data fetch - intentionally skipped this code
}
Thanks in advance!!
I got solution by using below function:-
public void ApplyCreditsOnPrePayInvoices(string sMonth, string sYear)
{
IMsgSetRequest IMsgSetRequestToQB = null;
ICreditMemoQuery ICreditMemoQueryToQB = null;
string sInvoiceTxnId = string.Empty;
string sInvoiceNumber = string.Empty;
if (this.GetConnectedToQB())
{
try
{
IMsgSetRequestToQB = m_sessionManager.CreateMsgSetRequest("US", 8, 0);
ICreditMemoQueryToQB = IMsgSetRequestToQB.AppendCreditMemoQueryRq();
ICreditMemoQueryToQB.ORTxnQuery.TxnFilter.ORDateRangeFilter.ModifiedDateRangeFilter.FromModifiedDate.SetValue(DateTimecl.GetValue("1." + sMonth + sYear), true);
IMsgSetResponse IMsgSetResponseFromQB = m_sessionManager.DoRequests(IMsgSetRequestToQB);
IResponseList ICreditListMemoAvailable = IMsgSetResponseFromQB.ResponseList;
if (ICreditListMemoAvailable.Count > 0)
{
string sCustomerListIdQB = string.Empty;
string sCustomerAccountNumber = string.Empty;
string sQBImportPrepayAccounts = Path.Combine(Environment.CurrentDirectory, sMonth + sYear, "Step11_QBImport_PrepayAccounts.csv");
DataTable dtQBImportPrepayAccounts = Utilcl.GetDataTableFromCSVFile(sQBImportPrepayAccounts);
IResponse ICreditMemoAvailable = ICreditListMemoAvailable.GetAt(0);
ICreditMemoRetList iCreditMemoList = ICreditMemoAvailable.Detail as ICreditMemoRetList;
if (iCreditMemoList != null)
{
for (int iCtr = 0; iCtr <= iCreditMemoList.Count - 1; iCtr++)
{
ICreditMemoRet ICreditMemo = iCreditMemoList.GetAt(iCtr);
DataRow[] drInvoiceNos = dtQBImportPrepayAccounts.Select("RefNumber = '" + ICreditMemo.RefNumber.GetValue() + "'");
if (drInvoiceNos.Length > 0)
{
sInvoiceNumber = Stringcl.GetValue(drInvoiceNos[0]["RefNumber"]);
m_requestMsgSet.ClearRequests();
m_requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue;
IReceivePaymentAdd IReceivePayment = m_requestMsgSet.AppendReceivePaymentAddRq();
sInvoiceTxnId = this.GetQBInvoiceTxnIDList(ICreditMemo.CustomerRef.FullName.GetValue()); //To get the Transaction ID of Invoice
IReceivePayment.CustomerRef.FullName.SetValue(Stringcl.GetValue(ICreditMemo.CustomerRef.FullName.GetValue()));
IAppliedToTxnAdd IAppliedToTxnAddress = IReceivePayment.ORApplyPayment.AppliedToTxnAddList.Append();
IAppliedToTxnAddress.TxnID.SetValue(sInvoiceTxnId);
ISetCredit ISetCreditToInvoice = IAppliedToTxnAddress.SetCreditList.Append();
ISetCreditToInvoice.CreditTxnID.SetValue(ICreditMemo.TxnID.GetValue());
ISetCreditToInvoice.AppliedAmount.SetValue(ICreditMemo.TotalAmount.GetValue());
IMsgSetResponse responseApplyCredit = m_sessionManager.DoRequests(m_requestMsgSet);
DataSet dsInvoice = this.GetExtractResponseFromQB(responseApplyCredit);
string sQueryResponse = Stringcl.GetValue(dsInvoice.Tables["ReceivePaymentAddRs"].Rows[0]["statusMessage"]);
if (sQueryResponse != "Status OK")
{
Utilcl.LogMessage("QB Credit Memo Query Response: " + sQueryResponse);
}
}
}
}
}
}
catch (Exception ex)
{
Utilcl.LogMessage(ex);
}
finally
{
if (IMsgSetRequestToQB != null)
{
Marshal.FinalReleaseComObject(IMsgSetRequestToQB);
}
if (ICreditMemoQueryToQB != null)
{
Marshal.FinalReleaseComObject(ICreditMemoQueryToQB);
}
}
}
}
I am trying to create functionality to copy data from one order to another. Here is the code that copies the data:
protected void copySeminarIDButton_Click(object sender, EventArgs e)
{
try
{
//show some message incase validation failed and return
String seminarID = this.copySeminarIDText.Text;
Int32 id;
try
{
id = Convert.ToInt32(seminarID);
} catch (Exception e2)
{
return;
}
//copy over all the registration types now for the entered id
using (SeminarGroupEntities db = new SeminarGroupEntities())
{
var seminars = db.seminars.Where(x => x.id == id);
if (seminars.Any())
{
var s = seminars.First();
//Load RegTypes
try
{
var regList = s.seminar_registration_type
.OrderBy(x => x.sort)
.ToList()
.Select(x => new seminarRegistrationTypeListing
{
id = x.id,
amount = x.amount,
description = x.description,
feeTypeId = x.feeTypeId,
method = x.method,
promoCodes = PromoCodesToString(x.xref_reg_type_promo.Select(z => z.promoId).ToList()),
title = x.title,
isPreorder = x.isPreorder,
sort = x.sort
});
this.dlTypes.DataSource = regList;
this.dlTypes.DataBind();
}
catch (Exception ex)
{
Response.Write("RegTypes: " + ex.Message);
}
} else
{
return;
}
}
}
catch (Exception m)
{
}
}
The user will enter a ID of the invoice they want to copy from. The above code copies pull the right data from the invoice and loads it on the page. When i click save the data is being saved.
The problem that is occurring is that the invoice that i copy data from will no longer have the data any more. So basically instead of copying the data its actually moving the data to the new invoice. I want to copy.
Here is my Save code.
private void SaveRegTypes(int seminarId)
{
//Reg Types
using (SeminarGroupEntities db = new SeminarGroupEntities())
{
try
{
var s = db.seminars.Where(x => x.id == seminarId).First();
var msg = "alert('Saving:" + seminarId + "');";
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "Data Copied...", msg, true);
this.copySeminarIDText.Text = msg;
//s.seminar_registration_type.Clear();
foreach (DataListItem dli in this.dlTypes.Items)
{
String sId = ((HiddenField)dli.FindControl("hdnId")).Value;
var reg = new seminar_registration_type();
if ((sId != "") && (sId != "0"))
{
Int32 id = Convert.ToInt32(sId);
reg = db.seminar_registration_type.Where(x => x.id == id).Single();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "Data Copied...", "alert('hidded field id is empty.');", true);
}
else
{
db.seminar_registration_type.Add(reg);
}
reg.feeTypeId = Convert.ToInt32(((DropDownList)dli.FindControl("ddlRegType")).SelectedItem.Value);
reg.amount = Convert.ToDecimal(((TextBox)dli.FindControl("txtPrice")).Text);
reg.title = ((DropDownList)dli.FindControl("ddlRegType")).SelectedItem.Text;
reg.description = ((TextBox)dli.FindControl("txtRegDesc")).Text;
reg.method = Convert.ToInt32(((DropDownList)dli.FindControl("ddlDeliveryMethod")).Text);
reg.promocode = null;
reg.isPreorder = Convert.ToBoolean(((CheckBox)dli.FindControl("chkPreorder")).Checked);
reg.sort = 1;
reg.seminarId = seminarId;
string sort = ((TextBox)dli.FindControl("txtRTSort")).Text;
try
{
reg.sort = Convert.ToInt32(sort);
}
catch (Exception ex) { }
//Do Promo Codes
Repeater rptPromocodes = (Repeater)dli.FindControl("rptPromoCodesList");
reg.xref_reg_type_promo.Clear();
foreach (RepeaterItem ri in rptPromocodes.Items)
{
try
{
Int32 id = Convert.ToInt32(((HiddenField)ri.FindControl("hdnCodeId")).Value);
DateTime? expires = null;
try
{
HiddenField exp = (HiddenField)ri.FindControl("hdnExpirationDate");
if (!String.IsNullOrWhiteSpace(exp.Value))
expires = Convert.ToDateTime(((HiddenField)ri.FindControl("hdnExpirationDate")).Value);
}
catch (Exception ex) { }
var code = db.promo_code.Where(x => x.id == id).First();
reg.xref_reg_type_promo.Add(new xref_reg_type_promo
{
expiration = expires,
promoId = code.id
});
}
catch (Exception ex) { }
}
db.SaveChanges();
((HiddenField)dli.FindControl("hdnId")).Value = reg.id.ToString();
}
}
catch (Exception ex)
{
String err = ex.Message;
}
}
}
Veiculo veiculo = new Veiculo();
veiculo.codigoUsuario = usuario.codigoUsuario;
veiculo.codigoTipoVeiculo = Convert.ToInt32(ddlTipoVeiculo.SelectedValue);
veiculo.codigoTipoMarca = Convert.ToInt32(ddlTipoMarca.SelectedValue);
veiculo.codigoTipoModelo = Convert.ToInt32(ddlTipoModelo.SelectedValue);
veiculo.codigoTipoCombustivel = Convert.ToInt32(ddlTipoCombustivel.SelectedValue);
veiculo.codigoTipoCambio = Convert.ToInt32(ddlTipoCambio.SelectedValue);
//veiculo.codigoTipoVersao = Convert.ToInt32(ddlTipoVersao.SelectedValue);
veiculo.AnoFabricacao = Convert.ToInt32(ddlDataFabricacao.SelectedValue);
veiculo.AnoModelo = Convert.ToInt32(ddlDataModelo.SelectedValue);
veiculo.Valor = Convert.ToDecimal(txtValor.Text);
veiculo.Cor = ddlCor.SelectedValue;
veiculo.Portas = Convert.ToInt32(ddlPortas.SelectedValue);
veiculo.Destaque = true;
veiculo.Ativo = true;
veiculo.Kilometragem = txtKilometragem.Text;
veiculo.DataCadastro = DateTime.Now;
veiculo.DataVencimento = DateTime.Now.AddMonths(1);
try
{
ctx.AddToVeiculo(veiculo);
ctx.SaveChanges();
AdicionarOpcionais(veiculo);
SaveImage(FUImagemPrincipal, veiculo);
SaveImage(FUSegundaImagem, veiculo);
SaveImage(FUTerceiraImagem, veiculo);
SaveImage(FUQuartaImagem, veiculo);
SaveImage(FUQuintaImagem, veiculo);
SaveImage(FUSextaImagem, veiculo);
}
catch (Exception)
{
}
THE SAVE IMAGE METHOD
private void SaveImage(FileUpload FileUpload, Veiculo veiculo)
{
// Upload Original Image Here
string uploadFileName = "";
string uploadFilePath = "";
VeiculoImagem veiculoImagem = new VeiculoImagem();
if (FileUpload.HasFile)
{
string ext = Path.GetExtension(FUImagemPrincipal.FileName).ToLower();
if (ext == ".jpg" || ext == ".jpeg" || ext == ".gif" || ext == ".png")
{
uploadFileName = Guid.NewGuid().ToString() + ext;
uploadFilePath = Path.Combine(Server.MapPath("~/upload"), uploadFileName);
try
{
veiculoImagem.Url = "/upload/" + uploadFileName;
veiculoImagem.codigoVeiculo = veiculo.codigoVeiculo;
ctx.AddToVeiculoImagem(veiculoImagem);
ctx.SaveChanges();
FileUpload.SaveAs(uploadFilePath);
}
catch (Exception)
{
Alert.Visible = true;
lbAlert.Text = "Erro, tente novamente.";
}
}
else
{
Alert.Visible = true;
lbAlert.Text = "Tipo de arquivo selecionado não permitido.";
}
}
}
How do i rollback if dont save the images (enter on else)? Because it save the veiculo, but dont save the images...
I don't know if my question is clearly... But please, help me!