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();
}
}
}
Related
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
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();
}
}
}
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.Net;
using System.IO;
using HtmlAgilityPack;
using mshtml;
using System.Text.RegularExpressions;
using System.IO.Compression;
namespace Extract_Images
{
public partial class Form1 : Form
{
private int numberoflinks = 13;
private int currentLinkNumber = 0;
private string mainlink;
private WebBrowser webBrowser1;
private bool firsturltonav = false;
public Form1()
{
InitializeComponent();
webBrowser1 = new WebBrowser();
webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
label1.Text = "Number of links: ";
mainlink = "http://www.test.com";
}
private void ProcessFirstLink()
{
string firstLink = mainlink;
firsturltonav = true;
webBrowser1.Navigate(firstLink);
}
private void ProcessNextLink()
{
if (currentLinkNumber < numberoflinks)
{
currentLinkNumber++;
string linktonav = mainlink + "index"+currentLinkNumber.ToString() + ".html";
label1.Text = currentLinkNumber.ToString();
webBrowser1.Navigate(linktonav);
}
}
int count = 0;
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
mshtml.HTMLDocument objHtmlDoc = (mshtml.HTMLDocument)webBrowser1.Document.DomDocument;
string pageSource = objHtmlDoc.documentElement.innerHTML;
if (firsturltonav == true)
ParseNumberOfLinks();
string[] hrefs = this.webBrowser1.Document.Links.Cast<HtmlElement>()
.Select(a => a.GetAttribute("href")).Where(h => h.Contains(".jpg")).ToArray();
foreach(string a in hrefs)
{
var result = GetImageAsync(a);
result.ContinueWith(task =>
{
task.Result.Save(#"C:\images\file" + count + ".jpg");
pictureBox1.Image = task.Result;
count++;
label2.Invoke(new MethodInvoker(delegate { label2.Text = count.ToString(); }));
});
}
ProcessNextLink();
}
public async Task<Image> GetImageAsync(string url)
{
var tcs = new TaskCompletionSource<Image>();
Image webImage = null;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null)
.ContinueWith(task =>
{
var webResponse = (HttpWebResponse)task.Result;
Stream responseStream = webResponse.GetResponseStream();
if (webResponse.ContentEncoding.ToLower().Contains("gzip"))
responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
else if (webResponse.ContentEncoding.ToLower().Contains("deflate"))
responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
if (responseStream != null) webImage = Image.FromStream(responseStream);
tcs.TrySetResult(webImage);
webResponse.Close();
responseStream.Close();
});
return tcs.Task.Result;
}
private void ParseNumberOfLinks()
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
ProcessNextLink();
}
}
}
The exception is on the line:
task.Result.Save(#"C:\images\file" + count + ".jpg");
The first two images are saved fine but then the exception is thrown:
A generic error occurred in GDI+
If i'm using try and catch i see in the StackTrace:
at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
at System.Drawing.Image.Save(String filename, ImageFormat format)
at System.Drawing.Image.Save(String filename)
at Extract_Images.Form1.b__2(Task`1 task) in d:\C-Sharp\Extract_Images\Extract_Images\Extract_Images\Form1.cs:line 76
Line 76 is:
task.Result.Save(#"C:\images\file" + count + ".jpg");
I am trying to send custom commands to a service using a windows form. The command I am trying to send is trying to place a file in Isolated Storage. Below is my source code.
Form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Project2Service;
namespace Project2
{
public partial class Form1 : Form
{
public Service1 s = new Service1();
public ServiceInstaller si = new ServiceInstaller();
public ProjectInstaller pi = new ProjectInstaller();
public ServiceController sc = new ServiceController("Project2Service");
private string[] isoType;
string machineName = System.Windows.Forms.SystemInformation.ComputerName;
public Form1()
{
InitializeComponent();
isoType = new string[] { "User", "Assembly And Domain"};
cboIsoType.Items.AddRange(isoType);
cboIsoType.SelectedIndex = 0;
btnContinue.Enabled = false;
btnPause.Enabled = false;
btnStop.Enabled = false;
}
public void Labels()
{
lblMachine.Text = machineName;
lblSName.Text = s.ServiceName;
lblSType.Text = si.StartType.ToString();
lblSStatus.Text = sc.Status.ToString();
lblPause.Text = sc.CanPauseAndContinue.ToString();
lblShutdown.Text = sc.CanShutdown.ToString();
lblStop.Text = sc.CanStop.ToString();
}
private void btnStart_Click(object sender, EventArgs e)
{
//Controller.Refresh(); //Gets the current status of service
//if (Controller.Status == ServiceControllerStatus.Stopped)
//{
// Controller.Start();
//}
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running);
Labels();
btnStart.Enabled = false;
btnContinue.Enabled = false;
btnStop.Enabled = true;
btnPause.Enabled = true;
}
private void btnStop_Click(object sender, EventArgs e)
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped);
Labels();
btnStart.Enabled = true;
btnContinue.Enabled = false;
btnPause.Enabled = false;
btnStop.Enabled = false;
}
private void btnPause_Click(object sender, EventArgs e)
{
sc.Pause();
sc.WaitForStatus(ServiceControllerStatus.Paused);
Labels();
btnPause.Enabled = false;
btnContinue.Enabled = true;
btnStart.Enabled = false;
btnStop.Enabled = true;
}
private void btnContinue_Click(object sender, EventArgs e)
{
sc.Continue();
sc.WaitForStatus(ServiceControllerStatus.Running);
Labels();
btnStop.Enabled = true;
btnStart.Enabled = false;
btnPause.Enabled = true;
btnContinue.Enabled = false;
}
private void btnSubmit_Click(object sender, EventArgs e)
{
if (cboIsoType.SelectedItem.ToString() == "User")
{
sc.ExecuteCommand(128);
}
}
}
}
Service
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace Project2Service
{
public partial class Service1 : ServiceBase
{
public enum ServiceCustomCommands { Command1 = 128, Command2 = 129 };
//private IsolatedStorageScope iso;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
//iso = IsolatedStorageScope.User | IsolatedStorageScope.Domain;
FileSystemWatcher Watcher = new FileSystemWatcher(#"C:\Users\Martin\Desktop\Project2\ServiceTest");
Watcher.EnableRaisingEvents = true;
Watcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName;
Watcher.Changed += new FileSystemEventHandler(Watcher_Changed);
Watcher.Created += new FileSystemEventHandler(Watcher_Created);
Watcher.Deleted += new FileSystemEventHandler(Watcher_Deleted);
Watcher.Renamed += new RenamedEventHandler(Watcher_Renamed);
WriteServiceInfo("Service Started!");
}
// This event is raised when a file is changed
private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Changed!");
DirectoryInfo d = new DirectoryInfo(#"C:\Users\Martin\Desktop\Project2\ServiceTest");//Assuming Watch is your Folder
FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
string str = "";
foreach (FileInfo file in Files)
{
str = str + ", " + file.Name;
str = str + ", " + file.LastWriteTime;
str = str + ", " + file.CreationTime;
str = str + ", " + file.Length;
WriteServiceInfo(file.Name);
WriteServiceInfo(file.LastWriteTime.ToString());
WriteServiceInfo(file.CreationTime.ToString());
WriteServiceInfo(file.Length.ToString());
}
}
private void Watcher_Created(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Created!");
}
private void Watcher_Deleted(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Deleted!");
}
private void Watcher_Renamed(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Renamed!");
}
private void WriteServiceInfo(string info)
{
FileStream fs = new FileStream(#"C:\Users\Martin\Desktop\Project2\WindowsServiceLog.txt",
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(info + "\n");
m_streamWriter.Flush();
m_streamWriter.Close();
}
protected override void OnStop()
{
WriteServiceInfo("Service Stopped!");
}
protected override void OnCustomCommand(int command)
{
switch ((ServiceCustomCommands)command)
{
case ServiceCustomCommands.Command1:
//Command1 Implementation
IsolatedStorageFile isoFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null);
IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("LaptopInfo.txt", FileMode.Append, FileAccess.Write, isoFile);
using (StreamWriter writer = new StreamWriter(isoStream))
{
writer.WriteLine("Data");
}
//iso = IsolatedStorageScope.User;
break;
case ServiceCustomCommands.Command2:
//iso = IsolatedStorageScope.User | IsolatedStorageScope.Assembly;
break;
default:
break;
}
}
}
}
sc.ExecuteCommand(128); in the submit button method does not seem to fire.
This worked just fine for me so I surmise its your code not hitting the call to execute the command. I took your code, made it a bit easier.
For example - stripping out all the stuff above - this code below worked and the text file appeared with the "Command Received" in it.
In your case it could be that you aren't closing the file. Try this:
using (
IsolatedStorageFile isoFile =
IsolatedStorageFile.GetStore(
IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly,
null, null))
{
IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("LaptopInfo.txt",
FileMode.Append, FileAccess.Write, isoFile);
using (StreamWriter writer = new StreamWriter(isoStream))
{
writer.WriteLine("Data");
}
WriteServiceInfo("data written to isolated storage");
isoFile.Close();
}
I changed the submit button to simply send the command, I'd suggest the same
private void btnSubmit_Click(object sender, EventArgs e)
{
sc.ExecuteCommand(128);
}
Service code is as follows
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace Project2Service
{
public partial class Service1 : ServiceBase
{
public enum ServiceCustomCommands { Command1 = 128, Command2 = 129 };
//private IsolatedStorageScope iso;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
WriteServiceInfo("Service Started!");
}
// This event is raised when a file is changed
private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Changed!");
}
private void Watcher_Created(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Created!");
}
private void Watcher_Deleted(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Deleted!");
}
private void Watcher_Renamed(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Renamed!");
}
private void WriteServiceInfo(string info)
{
FileStream fs = new FileStream(#"C:\Users\Adam\Desktop\WindowsServiceLog.txt",
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(info + "\n");
m_streamWriter.Flush();
m_streamWriter.Close();
}
protected override void OnStop()
{
WriteServiceInfo("Service Stopped!");
}
protected override void OnCustomCommand(int command)
{
WriteServiceInfo("Command received");
switch ((ServiceCustomCommands)command)
{
case ServiceCustomCommands.Command1:
//Command1 Implementation
IsolatedStorageFile isoFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null);
IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("LaptopInfo.txt", FileMode.Append, FileAccess.Write, isoFile);
using (StreamWriter writer = new StreamWriter(isoStream))
{
writer.WriteLine("Data");
}
//iso = IsolatedStorageScope.User;
break;
case ServiceCustomCommands.Command2:
//iso = IsolatedStorageScope.User | IsolatedStorageScope.Assembly;
break;
default:
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.