I made a application with iTextSharp to put numbers on a PDF file.
As you will see in the following code, my application just can do this, only if the file is in a specific directory.
So I made an "Other" button where the user can select a file.
What I want to do now is, that the chosen file will download the converted PDF.
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace NummerierePDF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
byte[] bytes = File.ReadAllBytes(#"L:\Users\user\Documents\PDFnummerieren\PDF.pdf");
iTextSharp.text.Font blackFont = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
using (MemoryStream stream = new MemoryStream())
{
PdfReader reader = new PdfReader(bytes);
using (PdfStamper stamper = new PdfStamper(reader, stream))
{
int pages = reader.NumberOfPages;
for (int i = 1; i <= pages; i++)
{
ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_RIGHT, new Phrase(i.ToString(), blackFont), 568f, 15f, 0);
}
}
bytes = stream.ToArray();
}
File.WriteAllBytes(#"L:\Users\user\Documents\PDFnummerieren\PDF1.pdf", bytes);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button3_Click(object sender, EventArgs e)
{
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string fileToOpen = FD.FileName;
System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);
System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
}
}
}
}
So File.WriteAllBytes(#"L:\Users\user\Documents\PDFnummerieren\PDF1.pdf", bytes);
can stay because it doesn't matter where the file will be downloaded after it's converted.
But File.ReadAllBytes(#"L:\Users\user\Documents\PDFnummerieren\PDF.pdf");
shouldn't be a specific directory, it should get the chosen file from button3.
As you probably noticed I'm new into programming so I thought maybe I could do this: File.ReadAllBytes(fileToOpen);
to get the string. Though that doesn't do his job.
Thanks for your time.
If you want to use a variable between methods of the same class then you need to declare a private and non-static class level variable (called also Instance Field). This is visible to every method of the class.
public partial class Form1 : Form
{
// Here declare a variable visible to all methods inside the class but
// not outside the class. Init it with an empty string
private string theFile = "";
private void button1_Click(object sender, EventArgs e)
{
// When you click the button1 check if the variable
// has been set to something in the button3 click event handler
if(string.IsNullOrEmpty(theFile) || !File.Exists(theFile))
return;
// Now you can use it to load the file and continue with the code
// you have already written
byte[] bytes = File.ReadAllBytes(theFile);
......
......
}
private void button3_Click(object sender, EventArgs e)
{
// The only job of button3 is to select the file to work on
// as you can see we can use the variable also here
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
theFile = FD.FileName;
}
}
But do you really need a separate button for this? I mean you could put the three lines of code in the button3 directly in at the start of the code in button1 and remove the superfluos (at this point) button3
I suggest you to read some docs on variable's Scope and Lifetime
Try this
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace NummerierePDF
{
public partial class Form1 : Form
{
string fileToOpen = string.Empty;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrWhiteSpace(fileToOpen)) return;
byte[] bytes = File.ReadAllBytes(fileToOpen);
iTextSharp.text.Font blackFont = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
using (MemoryStream stream = new MemoryStream())
{
PdfReader reader = new PdfReader(bytes);
using (PdfStamper stamper = new PdfStamper(reader, stream))
{
int pages = reader.NumberOfPages;
for (int i = 1; i <= pages; i++)
{
ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_RIGHT, new Phrase(i.ToString(), blackFont), 568f, 15f, 0);
}
}
bytes = stream.ToArray();
}
File.WriteAllBytes(#"L:\Users\user\Documents\PDFnummerieren\PDF1.pdf", bytes);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button3_Click(object sender, EventArgs e)
{
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
fileToOpen = FD.FileName;
System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);
System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
}
}
}
}
I have put your variable to class scope and now you can access it from anywhere inside your class
Related
why can't I add a new item/object to my list in button (or combobox etc.) events? I mean, the events don't see my list if it's outside of the brackets...it's underlined in red... can you help me?
long story short: i want to add a new object by clicking the button
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.IO;
namespace Samochody
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
List<Samochod> ListaSamochodow = new List<Samochod>();
comboBox1.DataSource = ListaSamochodow;
comboBox1.DisplayMember = "Marka";
XmlRootAttribute oRootAttr = new XmlRootAttribute();
XmlSerializer oSerializer = new XmlSerializer(typeof(List<Samochod>), oRootAttr);
StreamWriter oStreamWriter = null;
oStreamWriter = new StreamWriter("samochody.xml");
oSerializer.Serialize(oStreamWriter, ListaSamochodow);
}
private void button1_Click(object sender, EventArgs e)
{
try
{
ListaSamochodow.Add(new Samochod(textBox1.Text, textBox2.Text, Convert.ToInt32(textBox3.Text)));
}
catch (Exception oException)
{
Console.WriteLine("Aplikacja wygenerowała następujący wyjątek: " + oException.Message);
}
}
I think you should instantiate your list globally and not under Form1_Load event.
that way it will be accessible all around your class (the window in this case).
This seems to work fine. You might need to set your textboxes to contain valid values when you start the form. also make sure that you make the list visible throughout your form1 class.
namespace Samochody
{
public partial class Form1 : Form
{
// make sure your list looks like this, created outside your functions.
List<Samochod> ListaSamochodow = new List<Samochod>();
public Form1()
{
InitializeComponent();
label1.Text = "the amount in your list is " + ListaSamochodow.Count.ToString();
textBox1.Text = "string here";
textBox2.Text = "string here";
textBox3.Text = "100";
}
private void Form1_Load(object sender, EventArgs e)
{
XmlRootAttribute oRootAttr = new XmlRootAttribute();
XmlSerializer oSerializer = new XmlSerializer(typeof(List<Samochod>), oRootAttr);
StreamWriter oStreamWriter = null;
oStreamWriter = new StreamWriter("samochody.xml");
oSerializer.Serialize(oStreamWriter, ListaSamochodow);
}
private void button1_Click_1(object sender, EventArgs e)
{
Samochod s = new Samochod(textBox1.Text, textBox2.Text, Convert.ToInt32(textBox3.Text));
ListaSamochodow.Add(s);
label1.Text = "the amount in your list is " + ListaSamochodow.Count.ToString();
}
}
}
This is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SmallStore
{
public partial class AddProduct : Form
{
private db_Entities db = new db_Entities();
private Byte[] byteBLOBData;
public AddProduct()
{
InitializeComponent();
comboCatagory.DataSource = db.Product_Type.ToList();
comboCatagory.DisplayMember = "Description";
comboCatagory.ValueMember = "Product_Type";
comboCatagory.Invalidate();
}
private void AddProduct_Load(object sender, EventArgs e)
{
//check the data type cant cast to int dont know why
//MessageBox.Show(comboCatagory.SelectedValue.GetType().ToString());
}
private void btnUpload_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
FileStream fsBLOBFile = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
byteBLOBData = new Byte[fsBLOBFile.Length];
fsBLOBFile.Read(byteBLOBData, 0, byteBLOBData.Length);
MemoryStream memBLOBData = new MemoryStream(byteBLOBData);
pictureBox1.Image = Image.FromStream(memBLOBData);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
Product product = new Product();
product.Description = txtDescription.Text;
product.Price = decimal.Parse(txtPrice.Text);
product.Image = byteBLOBData;
/*THIS IS THE PROBLEM*/
product.Product_Type = (int)comboCatagory.SelectedValue;
db.Products.Add(product);
db.SaveChanges();
}
}
}
i have been wracking my brain on this problem for 2 days now. i have a dbEntities model bound to a comboCatagory box in a Product SQL table. Product_type is of type int and description is a varchar(MAX). everything else is working. when i save "btnSave_Click" i get an invalid cast error. Can anyone please explain what i am doing wrong. i been using c# for a week i come from java and c/x86asm. im am very new to .net and entity framework. i know there are other ways to do this but i really like the EF. Thanks friends! also i did check other questions but they are not dealing with ef and data binding to combobox.
Here's the problem, you need "ProductType" not "Product_Type" in value member of the Combobox
public AddProduct()
{
InitializeComponent();
comboCatagory.DataSource = db.Product_Type.ToList();
comboCatagory.DisplayMember = "Description";
comboCatagory.ValueMember = "ProductType"; //Not Product_Type
comboCatagory.Invalidate();
}
This is the code that compiles i made a error in the first one
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SmallStore
{
public partial class AddProduct : Form
{
private db_Entities db = new db_Entities();
private Byte[] byteBLOBData;
public AddProduct()
{
InitializeComponent();
comboCatagory.DataSource = db.Product_Type.ToList();
comboCatagory.DisplayMember = "Product_Type";
comboCatagory.ValueMember = "Description";
comboCatagory.Invalidate();
}
private void AddProduct_Load(object sender, EventArgs e)
{
//check the data type cant cast to int dont know why
//MessageBox.Show(db.Product_Type.ToList().GetType().ToString());
}
private void btnUpload_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
FileStream fsBLOBFile = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
byteBLOBData = new Byte[fsBLOBFile.Length];
fsBLOBFile.Read(byteBLOBData, 0, byteBLOBData.Length);
MemoryStream memBLOBData = new MemoryStream(byteBLOBData);
pictureBox1.Image = Image.FromStream(memBLOBData);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
Product product = new Product();
product.Description = txtDescription.Text;
product.Price = decimal.Parse(txtPrice.Text);
product.Image = byteBLOBData;
/*this is the line in question*/
product.ProductType = (int)(comboCatagory.SelectedValue);
db.Products.Add(product);
db.SaveChanges();
}
}
}
I'm doing project in C# that read from a video file and convert it to subtitle text, but i want to get the start time for each text line so it can be shown in the video at the right time, i tried the AudioPosition but it not working well, is there a away to do this?
using System;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Speech.Recognition;
using System.Threading.Tasks;
namespace project
{
public partial class Form1 : Form
{
StringBuilder sb = new StringBuilder();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
string[] tokens;
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "WAV|*.wav";
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
}
SpeechRecognitionEngine sre = new SpeechRecognitionEngine();
Grammar gr = new DictationGrammar();
sre.LoadGrammar(gr);
sre.SetInputToWaveFile(#openFileDialog1.FileName);
while (true)
{
try
{
var recText = sre.Recognize();
sb.Append(recText.Audio.AudioPosition + " * ");
textBox4.Text = sb.ToString();
tokens = sb.ToString().Split('#');
for (int i = 0; i < tokens.Length - 1; i++)
{
textBox2.AppendText(tokens.Length.ToString());
textBox2.AppendText(i+" - "+tokens[i]);
textBox2.AppendText(Environment.NewLine);
}
}
catch (Exception ex)
{
break;
}
}
}
I wrote a simple image uploader in C#. Here's my code:
using System;
using System.Collections.Specialized;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
namespace Snappx
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
GlobalHook.HookManager.KeyUp += new KeyEventHandler(MyKeyUp);
CheckForIllegalCrossThreadCalls = false;
new Task(this.Hide).Start();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Environment.Exit(-1);
}
string ORIGINIM;
async void MyKeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.PrintScreen)
{
await GetImage();
e.Handled = true;
}
else e.Handled = false;
}
String img = #"temp";
async Task GetImage()
{
Rectangle bounds = Screen.GetBounds(Point.Empty);
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
}
bitmap.Save(img, ImageFormat.Png);
}
using (var w = new WebClient())
{
var values = new NameValueCollection { { "key", "85684005b7d4faa4c33ee480010d4982" }, { "image", Convert.ToBase64String(File.ReadAllBytes(img)) } };
notifyIcon1.ShowBalloonTip(3, "Uploading", "Uploading image to Imgur", ToolTipIcon.Info);
w.UploadProgressChanged += new UploadProgressChangedEventHandler(wc_UploadProgressChanged);
Task<byte[]> x = w.UploadValuesTaskAsync(new Uri("http://imgur.com/api/upload.xml"), values);
byte[] response = await x;
while (w.IsBusy) System.Threading.Thread.Sleep(500);
File.Delete(img);
ORIGINIM = Convert.ToString(XDocument.Load(new MemoryStream(response)));
ORIGINIM = ORIGINIM.Substring(ORIGINIM.LastIndexOf("<original_image>")).Replace("<original_image>", "");
ORIGINIM = ORIGINIM.Substring(0, ORIGINIM.LastIndexOf("</original_image>")).Replace("</original_image>", "");
Clipboard.SetText(ORIGINIM);
if (!File.Exists(#"Uploads.txt")) File.Create(#"Uploads.txt");
new StreamWriter(#"Uploads.txt").WriteLine(ORIGINIM);
notifyIcon1.ShowBalloonTip(3, "Done", "URL copied to clipboard.", ToolTipIcon.Info);
}
}
private void wc_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
int percentage = e.ProgressPercentage * 2;
notifyIcon1.ShowBalloonTip(3, "Uploading", (percentage).ToString() + "%", ToolTipIcon.Info);
}
}
}
First of all, when there is no Uploads.txt file, it returns an Exception handler. Then second time I run it, it creates it. Is there any simpler way to store it?
Second question:
Am I able to add two different options, one for capture full screen and one for select screen region.
How could I integrate it with my code? Could you post it?
Instead of (!File.Exists(#"Uploads.txt")) File.Create(#"Uploads.txt") try this
using (StreamWriter sw = new StreamWriter(File.Open(#"Uploads.txt", FileMode.OpenOrCreate)))
{
sw.WriteLine(ORIGINIM);
}
The reason why it worked on the second try is because you didn't create a lock on the file with File.Create - the existing logic opens the file, which creates a FileStream, then you attempt to open StreamWriter on the same file. You should instead create the StreamWriter by passing the FileStream into its constructor, as shown in the above example.
I'm having some trouble, somehow I get a "not allowed exception" and I can't seem to figure out what is wrong I know the answer is simple but I really can't spot what's wrong with my code...
it happens when I try to write something to the newly created file and I could imagine that it also will when it tries to read the file... any information would be acknowledged...
thx in advance
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; // ny
using System.Net;
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using Microsoft.Phone.Shell;
using System.IO; // ny
using System.IO.IsolatedStorage; // ny
namespace SmartSence
{
public partial class MainPage : PhoneApplicationPage
{
private static UTF8Encoding enc = new UTF8Encoding();
// Constructor
public MainPage()
{
InitializeComponent();
if (CreateStore().FileExists("Userdata\\Userdata.txt"))
{
mail.Text = ReadFile(CreateStore());
}
}
private void minknap_Click(object sender, RoutedEventArgs e)
{
string newusername;
newusername = Username.Text;
mytext1.Text = newusername;
string igen;
igen = "&password=";
string newpassword;
newpassword = mypassword.Password;
mypasswordblock.Text = newpassword;
WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri("http://www.smartsence.dk/winindexcheck.php?id=" + mytext1.Text + igen + mypasswordblock.Text, UriKind.Absolute);
webBrowserTask.Show();
}
private void signin_Click(object sender, RoutedEventArgs e)
{
string signin;
signin = mail.Text;
signintext.Text = signin;
string igen;
igen = "&password=";
string newpassword;
newpassword = mail.Text;
signintext.Text = newpassword;
if (!CreateStore().DirectoryExists("Userdata"))
{
CreateStore().CreateDirectory("Userdata");
if (!CreateStore().FileExists("Userdata\\data.txt"))
{
CreateStore().CreateFile("Userdata\\data.txt");
}
IsolatedStorageFileStream stream = new IsolatedStorageFileStream("Userdata\\Userdata.txt", FileMode.Create, CreateStore());
WriteToFile(CreateStore(), signin);
}
WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri("http://www.smartsence.dk/winindexcheck.php?id=" + signintext.Text + igen + signintext.Text, UriKind.Absolute);
webBrowserTask.Show();
}
private void minknap2_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/Info.xaml", UriKind.Relative));
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
}
private void info_Click(object sender, EventArgs e)
{
MessageBox.Show("SmartSence App 4.0 - Is free to use, it´s has never been easier to navigate around the web. Buy the app and get free VIP status forever - Please support us :) ");
}
private void VIP_Click(object sender, EventArgs e)
{
WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri("http://www.smartsence.dk/winindexappvipcheck2.php", UriKind.Absolute);
webBrowserTask.Show();
}
private void image1_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
}
#region NewMethods
private IsolatedStorageFile CreateStore()
{
IsolatedStorageFile lager = IsolatedStorageFile.GetUserStoreForApplication();
return lager;
}
private void WriteToFile(IsolatedStorageFile storeFile, string content)
{
IsolatedStorageFileStream fileStream = storeFile.OpenFile("Userdata\\Userdata.txt", FileMode.Open, FileAccess.Write); // Exception: not allowed on IsolatedStorageFile
using (StreamWriter writer = new StreamWriter(fileStream))
{
writer.WriteLine(content);
}
}
private string ReadFile(IsolatedStorageFile storeFile)
{
IsolatedStorageFileStream fileStream = storeFile.OpenFile("Userdata\\Userdata.txt", FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(fileStream))
{
return reader.ReadLine().Trim();
}
}
private void mail_Tap(object sender, GestureEventArgs e)
{
mail.Text = string.Empty;
}
#endregion
}
}
I think the issue is that you're not closing your IsolatedStorageFileStream, so the file is still open, and hence cannot be written, therefore throwing this exception. You should make sure to wrap your reads & writes in a using, or calling Dispose yourself.
public MainPage()
{
InitializeComponent();
if (CreateStore().FileExists("Userdata\\Userdata.txt"))
{
mail.Text = ReadFile(CreateStore()); //opens file and never closes it.
}
}
To fix this, you should use using statements.
private void WriteToFile(IsolatedStorageFile storeFile, string content)
{
using (IsolatedStorageFileStream fileStream = storeFile.OpenFile("Userdata\\Userdata.txt", FileMode.Open, FileAccess.Write){ // Exception: not allowed on IsolatedStorageFile
using (StreamWriter writer = new StreamWriter(fileStream))
{
writer.WriteLine(content);
}
}
}
private string ReadFile(IsolatedStorageFile storeFile)
{
using(IsolatedStorageFileStream fileStream = storeFile.OpenFile("Userdata\\Userdata.txt", FileMode.Open, FileAccess.Read){
using (StreamReader reader = new StreamReader(fileStream))
{
return reader.ReadLine().Trim();
}
}
}