LINQ Rollback in Multiple Tables - c#

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!

Related

Excel data reading from Stream and save to the database

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 ?

How to fill entry with missing when nothing was writte in in xamarin app?

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.

asynchronous datagrid view c#

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;
}
}

The code is giving error at MultiSheetsPdf

This is my code which create PDF of a dwg file but it gives me error near MultiSheetPdf. Please give me the solution for same.
I thought that linking is the problem but I am not able to identify please suggest me the solution.
namespace Plottings
{
public class MultiSheetsPdf
{
private string dwgFile, pdfFile, dsdFile, outputDir;
private int sheetNum;
private IEnumerable<Layout> layouts;
private const string LOG = "publish.log";
public MultiSheetsPdfPlot(string pdfFile, IEnumerable<Layout> layouts)
{
Database db = HostApplicationServices.WorkingDatabase;
this.dwgFile = db.Filename;
this.pdfFile = pdfFile;
this.outputDir = Path.GetDirectoryName(this.pdfFile);
this.dsdFile = Path.ChangeExtension(this.pdfFile, "dsd");
this.layouts = layouts;
}
public void Publish()
{
if (TryCreateDSD())
{
Publisher publisher = AcAp.Publisher;
PlotProgressDialog plotDlg = new PlotProgressDialog(false, this.sheetNum, true);
publisher.PublishDsd(this.dsdFile, plotDlg);
plotDlg.Destroy();
File.Delete(this.dsdFile);
}
}
private bool TryCreateDSD()
{
using (DsdData dsd = new DsdData())
using (DsdEntryCollection dsdEntries = CreateDsdEntryCollection(this.layouts))
{
if (dsdEntries == null || dsdEntries.Count <= 0) return false;
if (!Directory.Exists(this.outputDir))
Directory.CreateDirectory(this.outputDir);
this.sheetNum = dsdEntries.Count;
dsd.SetDsdEntryCollection(dsdEntries);
dsd.SetUnrecognizedData("PwdProtectPublishedDWF", "FALSE");
dsd.SetUnrecognizedData("PromptForPwd", "FALSE");
dsd.SheetType = SheetType.MultiDwf;
dsd.NoOfCopies = 1;
dsd.DestinationName = this.pdfFile;
dsd.IsHomogeneous = false;
dsd.LogFilePath = Path.Combine(this.outputDir, LOG);
PostProcessDSD(dsd);
return true;
}
}
private DsdEntryCollection CreateDsdEntryCollection(IEnumerable<Layout> layouts)
{
DsdEntryCollection entries = new DsdEntryCollection();
foreach (Layout layout in layouts)
{
DsdEntry dsdEntry = new DsdEntry();
dsdEntry.DwgName = this.dwgFile;
dsdEntry.Layout = layout.LayoutName;
dsdEntry.Title = Path.GetFileNameWithoutExtension(this.dwgFile) + "-" + layout.LayoutName;
dsdEntry.Nps = layout.TabOrder.ToString();
entries.Add(dsdEntry);
}
return entries;
}
private void PostProcessDSD(DsdData dsd)
{
string str, newStr;
string tmpFile = Path.Combine(this.outputDir, "temp.dsd");
dsd.WriteDsd(tmpFile);
using (StreamReader reader = new StreamReader(tmpFile, Encoding.Default))
using (StreamWriter writer = new StreamWriter(this.dsdFile, false, Encoding.Default))
{
while (!reader.EndOfStream)
{
str = reader.ReadLine();
if (str.Contains("Has3DDWF"))
{
newStr = "Has3DDWF=0";
}
else if (str.Contains("OriginalSheetPath"))
{
newStr = "OriginalSheetPath=" + this.dwgFile;
}
else if (str.Contains("Type"))
{
newStr = "Type=6";
}
else if (str.Contains("OUT"))
{
newStr = "OUT=" + this.outputDir;
}
else if (str.Contains("IncludeLayer"))
{
newStr = "IncludeLayer=TRUE";
}
else if (str.Contains("PromptForDwfName"))
{
newStr = "PromptForDwfName=FALSE";
}
else if (str.Contains("LogFilePath"))
{
newStr = "LogFilePath=" + Path.Combine(this.outputDir, LOG);
}
else
{
newStr = str;
}
writer.WriteLine(newStr);
}
}
File.Delete(tmpFile);
}
[CommandMethod("PlotPdf")]
public void PlotPdf()
{
Database db = HostApplicationServices.WorkingDatabase;
short bgp = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
try
{
Application.SetSystemVariable("BACKGROUNDPLOT", 0);
using (Transaction tr = db.TransactionManager.StartTransaction())
{
List<Layout> layouts = new List<Layout>();
DBDictionary layoutDict =
(DBDictionary)db.LayoutDictionaryId.GetObject(OpenMode.ForRead);
foreach (DBDictionaryEntry entry in layoutDict)
{
if (entry.Key != "Model")
{
layouts.Add((Layout)tr.GetObject(entry.Value, OpenMode.ForRead));
}
}
layouts.Sort((l1, l2) => l1.TabOrder.CompareTo(l2.TabOrder));
string filename = Path.ChangeExtension(db.Filename, "pdf");
MultiSheetsPdf plotter = new MultiSheetsPdf(filename, layouts);
plotter.Publish();
tr.Commit();
}
}
catch (System.Exception e)
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage("\nError: {0}\n{1}", e.Message, e.StackTrace);
}
finally
{
Application.SetSystemVariable("BACKGROUNDPLOT", bgp);
}
}
}
}
Here you go: (Try to note and understand the difference between your version and this version)
namespace Plottings
{
public class MultiSheetsPdf
{
private string dwgFile, pdfFile, dsdFile, outputDir;
private int sheetNum;
private IEnumerable<Layout> layouts;
private const string LOG = "publish.log";
public MultiSheetsPdf(){}
public MultiSheetsPdf(string pdfFile, IEnumerable<Layout> layouts)
{
Database db = HostApplicationServices.WorkingDatabase;
this.dwgFile = db.Filename;
this.pdfFile = pdfFile;
this.outputDir = Path.GetDirectoryName(this.pdfFile);
this.dsdFile = Path.ChangeExtension(this.pdfFile, "dsd");
this.layouts = layouts;
}
public void Publish()
{
if (TryCreateDSD())
{
Publisher publisher = AcAp.Publisher;
PlotProgressDialog plotDlg = new PlotProgressDialog(false, this.sheetNum, true);
publisher.PublishDsd(this.dsdFile, plotDlg);
plotDlg.Destroy();
File.Delete(this.dsdFile);
}
}
private bool TryCreateDSD()
{
using (DsdData dsd = new DsdData())
using (DsdEntryCollection dsdEntries = CreateDsdEntryCollection(this.layouts))
{
if (dsdEntries == null || dsdEntries.Count <= 0) return false;
if (!Directory.Exists(this.outputDir))
Directory.CreateDirectory(this.outputDir);
this.sheetNum = dsdEntries.Count;
dsd.SetDsdEntryCollection(dsdEntries);
dsd.SetUnrecognizedData("PwdProtectPublishedDWF", "FALSE");
dsd.SetUnrecognizedData("PromptForPwd", "FALSE");
dsd.SheetType = SheetType.MultiDwf;
dsd.NoOfCopies = 1;
dsd.DestinationName = this.pdfFile;
dsd.IsHomogeneous = false;
dsd.LogFilePath = Path.Combine(this.outputDir, LOG);
PostProcessDSD(dsd);
return true;
}
}
private DsdEntryCollection CreateDsdEntryCollection(IEnumerable<Layout> layouts)
{
DsdEntryCollection entries = new DsdEntryCollection();
foreach (Layout layout in layouts)
{
DsdEntry dsdEntry = new DsdEntry();
dsdEntry.DwgName = this.dwgFile;
dsdEntry.Layout = layout.LayoutName;
dsdEntry.Title = Path.GetFileNameWithoutExtension(this.dwgFile) + "-" + layout.LayoutName;
dsdEntry.Nps = layout.TabOrder.ToString();
entries.Add(dsdEntry);
}
return entries;
}
private void PostProcessDSD(DsdData dsd)
{
string str, newStr;
string tmpFile = Path.Combine(this.outputDir, "temp.dsd");
dsd.WriteDsd(tmpFile);
using (StreamReader reader = new StreamReader(tmpFile, Encoding.Default))
using (StreamWriter writer = new StreamWriter(this.dsdFile, false, Encoding.Default))
{
while (!reader.EndOfStream)
{
str = reader.ReadLine();
if (str.Contains("Has3DDWF"))
{
newStr = "Has3DDWF=0";
}
else if (str.Contains("OriginalSheetPath"))
{
newStr = "OriginalSheetPath=" + this.dwgFile;
}
else if (str.Contains("Type"))
{
newStr = "Type=6";
}
else if (str.Contains("OUT"))
{
newStr = "OUT=" + this.outputDir;
}
else if (str.Contains("IncludeLayer"))
{
newStr = "IncludeLayer=TRUE";
}
else if (str.Contains("PromptForDwfName"))
{
newStr = "PromptForDwfName=FALSE";
}
else if (str.Contains("LogFilePath"))
{
newStr = "LogFilePath=" + Path.Combine(this.outputDir, LOG);
}
else
{
newStr = str;
}
writer.WriteLine(newStr);
}
}
File.Delete(tmpFile);
}
[CommandMethod("PlotPdf")]
public void PlotPdf()
{
Database db = HostApplicationServices.WorkingDatabase;
short bgp = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
try
{
Application.SetSystemVariable("BACKGROUNDPLOT", 0);
using (Transaction tr = db.TransactionManager.StartTransaction())
{
List<Layout> layouts = new List<Layout>();
DBDictionary layoutDict =
(DBDictionary)db.LayoutDictionaryId.GetObject(OpenMode.ForRead);
foreach (DBDictionaryEntry entry in layoutDict)
{
if (entry.Key != "Model")
{
layouts.Add((Layout)tr.GetObject(entry.Value, OpenMode.ForRead));
}
}
layouts.Sort((l1, l2) => l1.TabOrder.CompareTo(l2.TabOrder));
string filename = Path.ChangeExtension(db.Filename, "pdf");
MultiSheetsPdf plotter = new MultiSheetsPdf(filename, layouts);
plotter.Publish();
tr.Commit();
}
}
catch (System.Exception e)
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage("\nError: {0}\n{1}", e.Message, e.StackTrace);
}
finally
{
Application.SetSystemVariable("BACKGROUNDPLOT", bgp);
}
}
}
}
Heads up. The method, PostProcessDSD, tests are too generic. Client contacted me complaining that one of his files was not plotting. It was named "SOUTH". The test for "OUT" in the string caused the issue. No errors were thrown. Just a good ol' fashion mystery.
Change all tests to include the "=". ie else if (str.Contains("OUT=")) { ...

Hidden Filed Value not maintained in asp.net

I am working in ASP.Net to download the Image and I use the following code:
Code:
Main Method:
protected void btndownload_Click(object sender, EventArgs e)
{
FlyerBean objFlyerBean = SaveFlyer();
if (objFlyerBean == null)
return;
BindData(objFlyerBean);
string downLoadUrl = CommonUtil.GetBaseUrl() + "Preview/flyerview.aspx?FID=" + objFlyerBean.Id + "&Token=" + objFlyerBean.UserId + "&Size=" +
objFlyerBean.PreviewSize;
int previewWidth = -1;
int previwHeight = -1;
switch (objFlyerBean.PreviewSize)
{
case "8-5X11":
previewWidth = 885;
previwHeight = 980;
break;
case "5X7":
previewWidth = 524;
previwHeight = 814;
break;
case "4X6":
previewWidth = 428;
previwHeight = 696;
break;
}
Thread th = new Thread(delegate()
{
byte[] imgbyte = objScrenShotHelper.GenerateScreenshot(downLoadUrl, previewWidth, previwHeight);
Response.ContentType = "image/png";
Response.AppendHeader("content-disposition", "attachment; filename=" + DateTime.Now.Ticks + ".png");
Response.BinaryWrite(imgbyte);
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
th.Join();
}
Inner Methods:
private FlyerBean SaveFlyer()
{
FlyerBean objFlyerBean = new FlyerBean();
objFlyerBean.Id = string.IsNullOrEmpty(hfFlyerId.Value) ? 0 : Convert.ToInt64(hfFlyerId.Value);
objFlyerBean.Header = flyerHeader.Text.Trim();
objFlyerBean.Caption = flyerCaption.Text.Trim();
objFlyerBean.ChannelId = string.IsNullOrEmpty(hfSelectedChannelId.Value) ? 0 : Convert.ToInt32(hfSelectedChannelId.Value);
objFlyerBean.ChannelColor = hfchannelColor.Value;
objFlyerBean.FlyerImageSize = hfFlyerSize.Value;
objFlyerBean.FlyerLogoImageSize = hfFlyerLogoSize.Value;
if (!string.IsNullOrEmpty(hfImgePath.Value))
{
objFlyerBean.ImagePath = hfImgePath.Value;
objFlyerBean.ImageName = hfImageName.Value;
}
if (!string.IsNullOrEmpty(hflogoPath.Value))
{
objFlyerBean.BusinessLogo = hflogoPath.Value;
objFlyerBean.LogoName = hflogoName.Value;
}
objFlyerBean.BusinessName = flyerBusinessName.Text.Trim();
objFlyerBean.BackGroundColor = hfbgcolor.Value;
objFlyerBean.PreviewSize = hfViewSize.Value;
objFlyerBean.FieldsOrder = hfFieldOrder.Value;
objFlyerBean.UserId = new Guid(Session["user_id"].ToString());
FlyerBean Result = objFlyerHelper.SaveFlyer(objFlyerBean);
hfFlyerId.Value = "0";
if (Result == null)
return Result;
if (Result.Id > 0)
{
hfFlyerId.Value = Result.Id.ToString();
ViewState["flyerId"] = hfFlyerId.Value;
}
return Result;
}
private void BindData(FlyerBean objFlyerBean)
{
if (objFlyerBean != null)
{
SetBreadCrumb(true);
hfFlyerId.Value = objFlyerBean.Id.ToString();
hfHeader.Value = objFlyerBean.Header;
hfCaption.Value = objFlyerBean.Caption;
hfImgePath.Value = objFlyerBean.ImagePath;
hfImageName.Value = objFlyerBean.ImageName;
hfSelectedChannelId.Value = objFlyerBean.ChannelId.ToString();
hfchannelColor.Value = objFlyerBean.ChannelColor;
hfFlyerSize.Value = objFlyerBean.FlyerImageSize;
hfFlyerLogoSize.Value = objFlyerBean.FlyerLogoImageSize;
hflogoPath.Value = objFlyerBean.BusinessLogo;
hflogoName.Value = objFlyerBean.LogoName;
hfBusinessName.Value = objFlyerBean.BusinessName;
hfbgcolor.Value = objFlyerBean.BackGroundColor;
perviewImg.ImageUrl = objFlyerBean.ImagePath;
previewLogo.ImageUrl = objFlyerBean.BusinessLogo;
hfViewSize.Value = objFlyerBean.PreviewSize;
string orderval = "";
foreach (FlyerElementOrderBean objorder in objFlyerBean.ElementOrderList)
{
if (string.IsNullOrEmpty(orderval))
{
orderval = orderval + (objorder.ElementOrder - 1);
}
else
{
orderval = orderval + "," + (objorder.ElementOrder - 1);
}
}
hfFieldOrder.Value = orderval;
}
else
{
SetBreadCrumb(false);
hfFlyerId.Value = "0";
hfHeader.Value = "Sign up for Special Offers";
hfCaption.Value = "and receive a FREE soda with purchase!";
hfSelectedChannelId.Value = "-2";
hfchannelColor.Value = "#f68700";
hfbgcolor.Value = "#ffffff";
hfFlyerSize.Value = "m";
hfFlyerLogoSize.Value = "m";
hfImgePath.Value = CommonUtil.GetBaseUrl() + "images/PrevieImgDefault.png";
hflogoPath.Value = CommonUtil.GetBaseUrl() + "images/PreviewLogo.png";
hfImageName.Value = "PrevieImgDefault.png";
hflogoName.Value = "PreviewLogo.png";
hfBusinessName.Value = "Pizza by Joe";
hfViewSize.Value = "8-5X11";
hfFieldOrder.Value = "0,1,2,3";
}
}
But the issue is that while doing the same the values for all the hidden values that I used on the page have been lost. Can anyone tell me the problem behind this or any alternative that I can use. Thanks in advance.

Categories

Resources