There is code in MSDN for printing rdlc without preview in web application but it does not work when i implement in IIS...is there any solution for this ....or any code which work in on print of rdlc without preview
here is the link http://msdn.microsoft.com/en-us/library/ms252091.aspx
It does not give any exception but also does not print the report
on MSDN they said create a console application but I need it in asp.net web application which run in IIS.
using System;
using System.IO;
using System.Data;
using System.Text;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.Collections.Generic;
using Microsoft.Reporting.WebForms;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Windows.Forms;
///<summary>
/// Summary description for Printing
/// this is the cool code found on MSDN site to print labels out without preview
/// abhay maini
///</summary>
publicclassPrinting : IDisposable
{
public Printing()
{
//
// TODO: Add constructor logic here
//
}
publicint m_currentPageIndex;
publicIList<Stream> m_streams;
// Routine to provide to the report renderer, in order to
// save an image for each page of the report.
publicStream CreateStream(string name,string fileNameExtension, Encoding encoding,string mimeType, bool willSeek)
{
string CurrentDrive;
CurrentDrive = Application.StartupPath.ToString();Stream stream = newFileStream("C:\\Labels\\" + name + "." + fileNameExtension, FileMode.Create);
m_streams.Add(stream);
return stream;
}
publicvoid Export(LocalReport report)
{
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>EMF</OutputFormat>" +
" <PageWidth>4.0in</PageWidth>" +
" <PageHeight>2.0in</PageHeight>" +
" <MarginTop>0.00in</MarginTop>" +
" <MarginLeft>0.00in</MarginLeft>" +
" <MarginRight>0.00in</MarginRight>" +
" <MarginBottom>0.00in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;m_streams = newList<Stream>();
report.Render("Image", deviceInfo, CreateStream, out warnings);
foreach (Stream stream in m_streams)
stream.Position = 0;
}
// Handler for PrintPageEvents
publicvoid PrintPage(object sender, PrintPageEventArgs ev)
{
Metafile pageImage = newMetafile(m_streams[m_currentPageIndex]);
ev.Graphics.DrawImage(pageImage, ev.PageBounds);
m_currentPageIndex++;
ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
}
publicvoid Print(string PrinterName)
{
// const string printerName = PrinterName;
if (m_streams == null || m_streams.Count == 0)
return;
PrintDocument printDoc = newPrintDocument();
printDoc.PrinterSettings.PrinterName = PrinterName;
if (!printDoc.PrinterSettings.IsValid)
{
string msg = String.Format(
"Can't find printer \"{0}\".", PrinterName);
MessageBox.Show(msg, "Print Error");return;
}
printDoc.PrintPage += newPrintPageEventHandler(PrintPage);
printDoc.Print();
}
// Create a local report for Report.rdlc, load the data,
// export the report to an .emf file, and print it.
publicvoid Run(string ReportName, string PrinterName, DataTable MyDataTable,string DSstring)
{
LocalReport report = newLocalReport();
report.ReportPath = ReportName;
report.DataSources.Clear();
report.DataSources.Add(newReportDataSource(DSstring, MyDataTable));
Export(report);
m_currentPageIndex = 0;
Print(PrinterName);
}
publicvoid Dispose()
{
if (m_streams != null)
{
foreach (Stream stream in m_streams)
stream.Close();
m_streams = null;
}
}
}
The above class can be called as below behind text change event:
protectedvoid TxtScanId_TextChanged(object sender, EventArgs e)
{
string sqlPrintScanID = "SELECT [ScanID], [LoadID], [tempVRMA], [CustPalletID], [TypeOfAsset] FROM [SerialScanDetail] WHERE [ScanID]=" + TxtScanId.Text + "";
string strConnection = ConfigurationManager.ConnectionStrings["RevisionConnectionString"].ToString();
SqlConnection conn = newSqlConnection(strConnection);
SqlDataAdapter da = newSqlDataAdapter();
da.SelectCommand = newSqlCommand(sqlPrintScanID, conn);
DataSet ds = newDataSet();
da.Fill(ds, "RevisionDataSet_SerialScanDetail");
//ReportViewer1.LocalReport.Refresh();
NewPrinting.Run(#"Reports\Report_ScanID.rdlc", "Eltron 2442", ds.Tables[0], "RevisionDataSet_SerialScanDetail");
}
I would suggest making use of the ReportViewer class.
ReportViewer reportViewer = new ReportViewer();
reportViewer.LocalReport.ReportPath = "ReportPath";
reportViewer.LocalReport.DataSources.Add(new ReportDataSource("data", data));
byte[] byteInfo;
byteInfo = reportViewer.LocalReport.Render("Image", deviceInfo, CreateStream, out warnings);
MemoryStream ms = new MemoryStream(byteInfo);
Image returnImage = Image.FromStream(ms);
returnImage is then an image data type that you can display/print.
I see you making a call to render but not assigning the value to use, this combined with not using a report viewer could be the problem.
The reason MSDN suggest making a console application is that it is a good idea to do a proof of concept in a basic program such as a console, get the result you want, then port that code into your desired environment.
Related
my name is omer and i m a student. i created a website and i wnat that the user will upload a video.
i used a ole object to add db and i succed but im having trouble to adding the video from db to the website. i dont want to save the file in folder and than use url. is it posiblle?
the code:
App_Data:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
public class MyVideoHelper
{
public MyVideoHelper()
{
}
//הפונקציה מקבלת מסלול של קובץ ומחזירה את הקובץ מומר לבייטים
public byte[] ConvertFileToByte(Stream file)
{
byte[] video = null;
BinaryReader br = new BinaryReader(file);
video = br.ReadBytes((int)(file.Length));
return video;
}
public FileStream ConvertByteToFile( byte[] file)
{
Stream stream = new MemoryStream(file);
FileStream filestream = stream as FileStream;
return filestream;
}
}
the sapx.cs
MyVideoHelper x = new MyVideoHelper();
string hero3 = Request.Form["hero3"];
if (Session["loggedIn"] != "true")
{
Response.Write("<script>alert('You Are not SignIN!');</script>");
return;
}
if ((video2.PostedFile != null) && (video2.PostedFile.ContentLength > 0))
{
Stream fs = video2.PostedFile.InputStream;
string command = "INSERT INTO videos (hero, file) VALUES( '" + hero3 + "','" + x.ConvertFileToByte(fs) + "')";
MyAdoHelper.DoQuery("omerwatchdb.accdb", command);
}
string sql = "SELECT file FROM videos";
DataTable info = MyAdoHelper.ExecuteDataTable("omerwatchdb.accdb", sql);
string omer;
omer = info.Rows[2][0].ToString();
byte[] bytes = Encoding.ASCII.GetBytes(omer);
vid = x.ConvertByteToFile(bytes);
If you are going to insert a video file into a database (and you should probably not), then you should treat it as binary data, i.e. a BLOB column. To insert data you should use "parameterized query" where specify the data for the SQL command separate from command itself.
you could follow an example on how to add a image file. The process will be identical for a video. And here is an article on how to retrieve the data.
I am trying to make a PDF form filling program. The program should get 2 id's from the PHP script, search the MySQL database, and fill the forms with info based of those two id's, but i cant make the PHP script pass arguments to the c# executable. Maybe u can help me out :)
PHP script :
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("documente", $con);
$idfirma;
$idagent;
$sql="SELECT * FROM `agenti` WHERE `Nume Agent` = '$_GET[numea]'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo "Date agent"."<br>";
echo $row['Nume Agent'];echo " | ";echo $row['Sigiliu'];echo " | ";echo $row['Legitimatie']."<br>"."<br>"."<br>"."<br>"."<br>";
$idagent=$row['ID'];
}
$sql1="SELECT * FROM `dateclienti` WHERE `Cod Fiscal` = '$_GET[codf]'";
$result = mysql_query($sql1);
while($row = mysql_fetch_array($result)) {
echo "Date Firma"."<br>";
echo $row['Nume Societate'];echo " | ";echo $row['Adresa Sediu'];echo " | ";echo $row['Cod Fiscal']."<br>";
$idfirma=$row['ID'];
}
exec("pdfgen\PdfGenerator\bin\Debug\PdfGenerator.exe $idfirma, $idagent 2>&1");
echo $idfirma."<br>"."<br>";
echo $idagent;
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con)
?>
c# scipt :
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
using System.IO;
using MySql.Data.MySqlClient;
namespace PdfGenerator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
FillForm();
ListFieldNames();
}
/// <summary>
/// List all of the form fields into a textbox. The
/// form fields identified can be used to map each of the
/// fields in a PDF.
/// </summary>
private void ListFieldNames()
{
string pdfTemplate = #"C:\xampp\htdocs\site\pdfgen\PdfGenerator\form.pdf";
// title the form
this.Text += " - " + pdfTemplate;
// create a new PDF reader based on the PDF template document
PdfReader pdfReader = new PdfReader(pdfTemplate);
// create and populate a string builder with each of the
// field names available in the subject PDF
StringBuilder sb = new StringBuilder();
foreach (DictionaryEntry de in pdfReader.AcroFields.Fields)
{
sb.Append(de.Key.ToString() + Environment.NewLine);
}
// Write the string builder's content to the form's textbox
textBox1.Text = sb.ToString();
textBox1.SelectionStart = 0;
}
private void FillForm()
{
string idagent1 = null;
string idfirma1 = null;
string[] args = System.Environment.GetCommandLineArgs();
if(args.Length !=0)
{
idfirma1 = args[1];
idagent1 = args[2];
}
using (var connection = new MySqlConnection("server = localhost; User Id = root; password = ; database = documente;"))
{
connection.Open();
string agenti = "SELECT `Nume Agent` FROM `agenti` WHERE `ID` = #id";
string name1 = null;
using (var cmd = new MySqlCommand(agenti, connection))
{
cmd.Parameters.AddWithValue("#id", idagent1);
MySqlDataReader rdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
foreach (DataRow row in dt.Rows)
{
string name = row["Nume Agent"].ToString();
name1 = name;
}
string pdfTemplate = #"C:\xampp\htdocs\site\pdfgen\PdfGenerator\form.pdf";
string newFile = #"C:\xampp\htdocs\site\pdfgen\PdfGenerator\completed_form.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(
newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
// set form pdfFormFields
// The first worksheet and W-4 form
pdfFormFields.SetField("topmostSubform[0].Page1[0].regcomert[0]", name1);
// flatten the form to remove editting options, set it to false
// to leave the form open to subsequent manual edits
pdfStamper.FormFlattening = true;
// close the pdf
pdfStamper.Close();
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace PdfGenerator
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
I am writing a demo proof of concept to add electronic signatures to existing PDFs. I am running into one weird problem that I don't get. It seems that adding the signature to some documents works fine while adding one to others does not work and a corrupt file is generated that Adobe Reader can not open.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using iText;
using iText.Kernel.Pdf;
using System.IO;
using iText.Layout;
using iText.Layout.Element;
using iText.Kernel.Geom;
using Org.BouncyCastle.Crypto.Tls;
using iText.Signatures;
using System.Collections.ObjectModel;
using Org.BouncyCastle.Pkcs;
using System.Security.Cryptography.X509Certificates;
using Org.BouncyCastle.Crypto;
using System.Security.Cryptography;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using iText.IO.Image;
namespace LTVSkilrikjaDemo
{
class Program
{
static void Main(string[] args)
{
string welcomeText = "Welcome to LTVSkilríkjaDemotolid!";
string pressEnterToTry = "Commands: 's' - sign, 'stop' - stops the programme";
Console.WriteLine(welcomeText);
Console.WriteLine(pressEnterToTry);
// Base directory prepared
string basedir = AppDomain.CurrentDomain.BaseDirectory;
int index = basedir.IndexOf(#"bin\");
basedir = basedir.Remove(index);
string readString = Console.ReadLine().ToLower();
while(!readString.Equals("stop"))
{
if(readString.Equals("c"))
{
string inFile = "Infile2.pdf";
string outFile = "Outfile2.pdf";
// Open PDF document and decide where to write the new document
PdfWorker worker = new PdfWorker();
worker.ReadPdf(basedir + "App_Data\\InFiles\\" + inFile, basedir + "App_Data\\OutFiles\\" + outFile);
// Start working on certificate
X509Store store = new X509Store("My");
store.Open(OpenFlags.ReadOnly);
Collection<Org.BouncyCastle.X509.X509Certificate> xcertificates = new Collection<Org.BouncyCastle.X509.X509Certificate>();
foreach (X509Certificate2 mCert in store.Certificates)
{
if (mCert.Subject.IndexOf("CN=Róbert") > -1)
{
xcertificates.Add(Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(mCert));
}
}
Org.BouncyCastle.X509.X509Certificate[] certificatesProcessed = new Org.BouncyCastle.X509.X509Certificate[xcertificates.Count];
for(int i = 0; i < xcertificates.Count; i++)
{
certificatesProcessed[i] = xcertificates[i];
}
var pk = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(store.Certificates[5].PrivateKey).Private;
try
{
worker.Sign(certificatesProcessed, pk, DigestAlgorithms.SHA1, PdfSigner.CryptoStandard.CADES, "No apparent raisin!", "Lost in Iceland", null, null, null, 0, true, basedir);
}
catch(Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Error! " + ex.Message + "\n\r" + ex.StackTrace);
if(ex.InnerException != null)
{
Console.WriteLine("Inner exception: " + ex.InnerException.Message);
}
Console.ForegroundColor = ConsoleColor.Gray;
}
}
else if(!readString.Equals("stop"))
{
Console.WriteLine("Command not understood. Understand only 's' and 'stop'.");
}
readString = Console.ReadLine();
}
Console.WriteLine("Goodbye!");
System.Threading.Thread.Sleep(500);
}
}
public class PdfWorker
{
private PdfDocument _document;
private string _source;
private string _dest;
public void ReadPdf(string source, string dest)
{
_source = source;
_dest = dest;
}
public void Sign(Org.BouncyCastle.X509.X509Certificate[] chain, Org.BouncyCastle.Crypto.ICipherParameters pk,
string digestAlgorithm, PdfSigner.CryptoStandard subfilter, string reason,
string location, Collection<ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient,
int estimatedSize, bool initial, string baseDir)
{
File.Copy(_source, _dest, true);
FileStream f = new FileStream(_dest, FileMode.Append);
try
{
PdfSigner signer = new PdfSigner(new PdfReader(_source), f, true);
_document = signer.GetDocument();
_document.AddNewPage();
// Work the last page
Rectangle pageSize = _document.GetLastPage().GetPageSizeWithRotation();
//PdfWriter w = _document.GetWriter();
//long currentPos = w.GetCurrentPos();
float llx = pageSize.GetWidth() - 350 - 20; //pageSize.GetWidth() / 2 - 350 / 2;
float lly = pageSize.GetHeight() - 50 - 20; // pageSize.GetHeight() / 2 - 150 / 2;
float urx = 350; //llx + 350;
float ury = 50; //lly + 150;
PdfSignatureAppearance appearance = signer.GetSignatureAppearance();
appearance.SetPageRect(new Rectangle(llx, lly, urx, ury));
appearance.SetReason(reason);
appearance.SetLocation(location);
byte[] imagebytes = File.ReadAllBytes(baseDir + "App_Data\\UndirskriftDemo.png");
// It is not possible to use the path as it contains Icelandic characters
// which itext chokes on. We use byte array instead
ImageData imgData = ImageDataFactory.Create(imagebytes);
Image img = new Image(imgData);
img = img.ScaleToFit(350.0f, 50.0f);
appearance.SetImage(imgData);
int pageCount = _document.GetNumberOfPages();
// Creating the appearance
if(initial == true)
{
signer.SetCertificationLevel(PdfSigner.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS);
}
appearance.SetPageNumber(pageCount);
Rectangle rect = new Rectangle(10, 50, 350, 50);
appearance.SetPageRect(rect).SetPageNumber(pageCount);
appearance.SetRenderingMode(PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION);
signer.SetFieldName(signer.GetNewSigFieldName());
// Creating the signature
IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);
signer.SignDetached(pks, chain, crlList, ocspClient, tsaClient, estimatedSize, subfilter);
Console.WriteLine("Signing successful!");
}
catch(Exception ex)
{
throw ex;
}
finally
{
_document.Close();
f.Close();
}
}
}
}
Please see the documents here then. Infile1.pdf I can not sign but Infile2.pdf is signed fine. Outfile1.pdf is the corrupt file.
https://app.box.com/s/52jqe8qirl80km6hunxucs00dntx70o5
What causes this? Is there something about the input PDF file or the above programme?
The problem is in your program, more exactly in your PdfWorker.Sign method:
File.Copy(_source, _dest, true);
FileStream f = new FileStream(_dest, FileMode.Append);
try
{
PdfSigner signer = new PdfSigner(new PdfReader(_source), f, true);
...
Here you first copy the file to sign to the destination and then append the PdfSigner output to it.
But that PdfSigner output is the complete signed PDF, i.e. the source plus an additional revision in which the signature is added. Thus, in the destination file you eventually have two copies of the source and then some signing additions generated under the assumptions that only one copy of the source precedes.
To fix this problem, simply remove the File.Copy(_source, _dest, true) operation and don't open the FileStream with FileMode.Append.
Even after this correction, signing of the OP's sample file "Infile1.PDF" still creates a broken PDF while signing the sample file "Infile2.pdf" now succeeds. The cause is the iText 7.0.0 bug explained in this answer which (as far as I can see) is fixed in 7.0.1. As the "Infile1.PDF" uses object streams while "Infile2.pdf" does not, only the former file is affected.
Im trying to modify a .dwg file and overwrite the .dwg file once done, all that without opening it in autocad. I've read about RealDWG but the goal here is not to be in a standalone mode. the autocad plugin runs from autocad and needs to modify and write to some .dwg files that are not opened in the current project. So far I create a Database object and Read the .dwg file into it but im having errors when I want to rewrite into it. Here is the code its in C#,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
namespace ModifyClosedDWG
{
public class DWGEditor
{
private static string filepath = #"E:\...\DrawingTest.dwg";
[CommandMethod("modifyDWG")]
public void addTextToDWG()
{
Database workingDB = HostApplicationServices.WorkingDatabase;
Editor ed = doc.Editor;
Database db = new Database(false, true);
try
{
db.ReadDwgFile(filepath, System.IO.FileShare.ReadWrite, false, "");
db.CloseInput(true);
HostApplicationServices.WorkingDatabase = db;
}
catch (Autodesk.AutoCAD.Runtime.Exception e)
{
ed.WriteMessage("\nUnable to read drawing file : " + e.StackTrace);
return;
}
using (BlockTable bt = db.BlockTableId.Open(OpenMode.ForRead) as BlockTable)
{
using (BlockTableRecord btr = bt[BlockTableRecord.ModelSpace].Open(OpenMode.ForWrite) as BlockTableRecord)
{
MText objText = new MText();
objText.SetDatabaseDefaults();
objText.Location = new Autodesk.AutoCAD.Geometry.Point3d(2, 2, 0);
objText.Contents = "added text in a closed .dwg file!";
objText.TextStyleId = db.Textstyle;
btr.AppendEntity(objText);
}
}
HostApplicationServices.WorkingDatabase = workingDB;
db.SaveAs(filepath, DwgVersion.Current);
}
}
}
the error output :
Autodesk.AutoCAD.Runtime.Exception: eWasOpenForWrite
at Autodesk.AutoCAD.DatabaseServices.Database.SaveAs(String fileName, DwgVersion version)
at ModifyClosedDWG.DWGEditor.addTextToDWG() in E:\PROJETS\ELI017\07 In Works documents\VisualC#Projects\ModifyClosedDWG\ModifyClosedDWG\DWGEditor.cs:line 64
at Autodesk.AutoCAD.Runtime.CommandClass.InvokeWorker(MethodInfo mi, Object commandObject, Boolean bLispFunction)
at Autodesk.AutoCAD.Runtime.CommandClass.InvokeWorkerWithExceptionFilter(MethodInfo mi, Object commandObject, Boolean bLispFunction)
at Autodesk.AutoCAD.Runtime.PerDocumentCommandClass.Invoke(MethodInfo mi, Boolean bLispFunction)
at Autodesk.AutoCAD.Runtime.CommandClass.CommandThunk.Invoke()
I found the solution so I'll put the new code here...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
namespace ModifyClosedDWG
{
public class DWGEditor
{
private static string filepath = #"E:\PROJETS\ELI017\07 In Works documents\dwg\DrawingTest.dwg";
[CommandMethod("modifyDWG")]
public void addTextToDWG()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
Database workingDB = HostApplicationServices.WorkingDatabase;
Database db = new Database(false, true);
try
{
db.ReadDwgFile(filepath, System.IO.FileShare.ReadWrite, false, "");
db.CloseInput(true);
HostApplicationServices.WorkingDatabase = db;
}
catch (Autodesk.AutoCAD.Runtime.Exception e)
{
ed.WriteMessage("\nUnable to open .dwg file : " + e.StackTrace);
return;
}
using (Transaction tr = db.TransactionManager.StartTransaction())
{
BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
MText objText = new MText();
objText.SetDatabaseDefaults();
objText.Location = new Autodesk.AutoCAD.Geometry.Point3d(2, 2, 0);
objText.Contents = "added text in a closed .dwg file!";
objText.TextStyleId = db.Textstyle;
btr.AppendEntity(objText);
tr.AddNewlyCreatedDBObject(objText, true);
tr.Commit();
}
HostApplicationServices.WorkingDatabase = workingDB;
db.SaveAs(filepath, DwgVersion.Current);
}
}
}
I have an application which uses open file dialog to open an excel file and then convert it to .txt and it works fine, almost. Currently it can only read tables with only numbers in them but I need to add a function so that it could also read letters. What should I change to make it able to read letters/words as well as numbers?
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : System.Windows.Window
{
public MainWindow()
{
InitializeComponent();
}
private void BtnFileOpen_Click(object sender, RoutedEventArgs e)
{
var fileDialog = new System.Windows.Forms.OpenFileDialog();
var result = fileDialog.ShowDialog();
switch (result)
{
case System.Windows.Forms.DialogResult.OK:
var file = fileDialog.FileName;
TxtFile.Text = file;
TxtFile.ToolTip = file;
break;
case System.Windows.Forms.DialogResult.Cancel:
default:
TxtFile.Text = null;
TxtFile.ToolTip = null;
break;
}
}
public void convert_Click(object sender, RoutedEventArgs e)
{
// Configure save file dialog box
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Save document
string filename = dlg.FileName;
exportExcelToTxt(TxtFile.Text, filename);
}
}
static void exportExcelToTxt(string excelFilePath, string outputTxtPath)
{
Dictionary<string, List<long>> values = new Dictionary<string, List<long>>();
using (OleDbConnection excelConnection = new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 XML;HDR=YES\"", excelFilePath)))
{
excelConnection.Open();
string firstSheet = getFirstSheetName(excelConnection);
using (OleDbCommand cmd = excelConnection.CreateCommand())
{
cmd.CommandText = string.Format("SELECT * FROM [{0}]", firstSheet);
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt); // Getting all the data in the sheet
foreach (DataRow item in dt.Rows)
{
List<long> toAdd = new List<long>();
string key = item[0] as string;
for (int i = 1; i < dt.Columns.Count; i++)
{
toAdd.Add(Convert.ToInt64(item[i]));
}
values.Add(key, toAdd); // Associating all the "numbers" to the "Name"
}
}
}
}
}
StringBuilder toWriteToTxt = new StringBuilder();
foreach (KeyValuePair<string, List<long>> item in values)
{
// Formatting the output
toWriteToTxt.Append(string.Format("{0}:", item.Key));
foreach (long val in item.Value.Distinct())
{
toWriteToTxt.AppendFormat("\t{0} * {1}\r\n", item.Value.Where(f => f == val).Count(), // Amount of occurrencies of each number
val);
}
}
// Writing the TXT
using (FileStream fs = new FileStream(outputTxtPath, FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(toWriteToTxt.ToString());
}
}
}
static string getFirstSheetName(OleDbConnection excelConnection)
{
using (DataTable ExcelTables = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" }))
{
return ExcelTables.Rows[0]["TABLE_NAME"].ToString();
}
}
}
}
You should not convert the values to long in this line:
toAdd.Add(Convert.ToInt64(item[i]));
Also replace all List<long> with List<string>, this should cover pretty much the issue.