Why MODI doesn't let me delete the processed file? - c#

private void button4_Click(object sender, EventArgs e)
{
OCR.recognize("test1.tif");
System.IO.File.Delete("test1.tif"); // <--- Problem on this line
}
....
public static string recognize(string filepath, MODI.MiLANGUAGES language =
MODI.MiLANGUAGES.miLANG_RUSSIAN)
{
if (!File.Exists(filepath)) return "error 1: File does not exist";
MODI.Document doc = new MODI.Document();
doc.Create(filepath);
doc.OCR(language, true, true);
MODI.Image image = (MODI.Image)doc.Images[0];
string result="";
foreach (MODI.Word worditems in image.Layout.Words)
{
result += worditems.Text + ' ';
// Processed image is ALWAYS a question
if (worditems.Text[worditems.Text.Length - 1] == '?') break;
}
doc.Close();
return result;
}
Problem is: File is used by another process.
How do I delete it after OCR?

Someone posted a solution for this:
public void Dispose()
{
doc.Close(false);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(doc);
doc = null;
GC.Collect();
}
Maybe it works for your case, too.

Related

Running macro to open file window in another program, need if statement that will execute when file is saved (c#)

private void pdfButton_Click(object sender, EventArgs e)
{
Operation.RunMacro("ExportPDF.cs");
if (Operation.RunMacro == )
{
MessageBox.Show("PDF files exported!");
pdfLabel.Text = pdfLabel.Text + " - DONE!";
pdfLabel.ForeColor = System.Drawing.Color.Green;
}
else
{
pdfLabel.Text = pdfLabel.Text + " WRONG!";
pdfLabel.ForeColor = System.Drawing.Color.Red;
}
}
This is my body of code, when the pdfButton is clicked, the macro will run opening up my file window. From there the user names their files and stores to a folder, how can I make the if statement execute when they store their files?
The method Operation.RunMacro needs to return the operation result. Then you have a condition you can test against:
class Operation
{
public bool RunMarco(string fileName)
{
try
{
// export logic
...
return true;
}
catch
{
return false;
}
}
}
then you can do:
private void pdfButton_Click(object sender, EventArgs e)
{
bool runMacroResult = Operation.RunMacro("ExportPDF.cs");
if (runMacroResult)
{
MessageBox.Show("PDF files exported!");
pdfLabel.Text = pdfLabel.Text + " - DONE!";
pdfLabel.ForeColor = System.Drawing.Color.Green;
}
else
{
pdfLabel.Text = pdfLabel.Text + " WRONG!";
pdfLabel.ForeColor = System.Drawing.Color.Red;
}
}

C# Launcher based on WebClient

I'm creating simple launcher for my other application and I need advise on logical part of the program. Launcher needs to check for connection, then check for file versions (from site), compare it with currently downloaded versions (if any) and if everything is alright, start the program, if not, update (download) files that differs from newest version. The files are:
program.exe, config.cfg and mapFolder. The program.exe and mapFolder must be updated, and config.cfg is only downloaded when there is no such file. Additionaly mapFolder is an folder which contains lots of random files (every new version can have totally different files in mapFolder).
For the file version I thought I would use simple DownloadString from my main site, which may contain something like program:6.0,map:2.3, so newest program ver is 6.0 and mapFolder is 2.3. Then I can use FileVersionInfo.GetVersionInfo to get the version of current program (if any) and include a file "version" into mapFolder to read current version.
The problem is I dont know how to download whole folder using WebClient and what's the best way to do what I want to do. I've tried to download the mapFolder as zip and then automatically unpack it, but the launcher need to be coded in .net 3.0.
Here is my current code, that's just a prototype to get familiar with whole situation, dont base on it.
`
WebClient wc = new WebClient();
string verifySite = "google.com/downloads/version";
string downloadSite = "google.com/downloads/program.exe";
Uri verifyUri, downloadUri = null;
string userVer, currVer = "";
string downloadPath = Directory.GetCurrentDirectory();
string clientName = "program.exe";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(FileDownloaded);
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(FileDownloadProgress);
chckAutorun.Checked = Properties.Settings.Default.autorun;
checkConnection();
if(!checkVersion())
downloadClient();
else
{
pbDownload.Value = 100;
btnPlay.Enabled = true;
lblProgress.Text = "updated";
if (chckAutorun.Checked)
btnPlay.PerformClick();
}
}
private bool checkConnection()
{
verifyUri = new Uri("http://" + verifySite);
downloadUri = new Uri("http://" + downloadSite);
WebRequest req = WebRequest.Create(verifyUri);
try
{
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
return true;
}
catch { }
verifyUri = new Uri("https://" + verifySite);
downloadUri = new Uri("https://" + downloadUri);
req = WebRequest.Create(verifyUri);
try
{
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
return true;
}
catch { }
return false;
}
private void downloadClient()
{
try
{
wc.DownloadFileAsync(downloadUri, Path.Combine(downloadPath, clientName));
}
catch { }
}
private bool checkVersion()
{
lblProgress.Text = "checking for updates";
try
{
currVer = FileVersionInfo.GetVersionInfo(Path.Combine(downloadPath, clientName)).FileVersion;
}
catch {
currVer = "";
}
try
{
userVer = wc.DownloadString(verifyUri);
}
catch {
userVer = "";
}
return currVer == userVer && currVer != "";
}
private void FileDownloaded(object sender, AsyncCompletedEventArgs e)
{
btnPlay.Enabled = true;
lblProgress.Text = "updated";
if (chckAutorun.Checked)
btnPlay.PerformClick();
}
private void FileDownloadProgress(object sender, DownloadProgressChangedEventArgs e)
{
long received = e.BytesReceived / 1000;
long toReceive = e.TotalBytesToReceive / 1000;
lblProgress.Text = string.Format("{0}KB {1}/ {2}KB", received, Repeat(" ", Math.Abs(-5 + Math.Min(5, received.ToString().Length))*2), toReceive);
pbDownload.Value = e.ProgressPercentage;
}
private void btnPlay_Click(object sender, EventArgs e)
{
btnPlay.Enabled = false;
if(checkVersion())
{
lblProgress.Text = "Starting...";
Process.Start(Path.Combine(downloadPath, clientName));
this.Close();
}
else
{
downloadClient();
}
}
public static string Repeat(string instr, int n)
{
if (string.IsNullOrEmpty(instr))
return instr;
var result = new StringBuilder(instr.Length * n);
return result.Insert(0, instr, n).ToString();
}
private void chckAutorun_CheckedChanged(object sender, EventArgs e)
{
Properties.Settings.Default.autorun = chckAutorun.Checked;
Properties.Settings.Default.Save();
}`
I've managed to achieve what I need by enabling autoindex on web server and download string of files in folder ending with .map .
string mapSite = wc.DownloadString(new Uri("http://" + mapsSite));
maps = Regex.Matches(mapSite, "<a href=\"(.*).map\">");
foreach (Match m in maps)
{
string mapName = m.Value.Remove(0, 9).Remove(m.Length - 11);
downloaded = false;
wc.DownloadFileAsync(new Uri("http://" + mapsSite + mapName), Path.Combine(downloadPath, #"mapFolder/" + mapName));
while (!downloaded) { }
}

c# windows phone -- text box doesn't understand foreign characters?

I'm building an app to access Google Translate for Windows Phone. I've noticed that for languages where the translated words will have foreign characters, the text box gets all screwed up and instead displays random symbols and such. Not sure why. Do I need to enable something on the text box?
Code:
private void btnTranslate_Click(object sender, RoutedEventArgs e)
{
string text = txtboxOriginal.Text;
string fromLanguage;
string toLanguage;
//Use Bing.
if ((bool)settings["translateIsBing"] == true)
{
if (string.IsNullOrWhiteSpace(text))
{
MessageBox.Show("Can't translate with nothing to translate. Please try again.");
}
else
{
}
}
//Use Google.
else if ((bool)settings["translateIsGoogle"] == true)
{
if (string.IsNullOrWhiteSpace(text))
{
MessageBox.Show("Can't translate with nothing to translate. Please try again.");
}
else
{
fromLanguage = this.getLanguageCodeGoogle(lstOriginalLanguages.SelectedIndex.ToString());
toLanguage = this.getLanguageCodeGoogle(lstTranslateToLanguages.SelectedIndex.ToString());
string url = "http://translate.google.com/translate_t?text=" + text + "&sl=" + fromLanguage + "&tl=" + toLanguage;
WebClient webclient = new WebClient();
webclient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webclient_DownloadStringCompleted);
webclient.DownloadStringAsync(new Uri(url, UriKind.RelativeOrAbsolute));
}
}
}
void webclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
try
{
Debug.WriteLine(e.Result);
string result = e.Result;
int startPosition = result.IndexOf("TRANSLATED_TEXT='");
int length = result.IndexOf(#"';INPUT") - startPosition;
string partial = result.Substring(startPosition, length);
Debug.WriteLine("Step 1: {0}", partial);
startPosition = partial.IndexOf("'") + 1;
length = partial.Length - startPosition;
string secondPartial = partial.Substring(startPosition, length);
Debug.WriteLine("Step 2: {0}", secondPartial);
translatedText = secondPartial;
txtboxOriginal.Text = secondPartial;
btnTranslate.Content = "Translated";
btnTranslate.IsEnabled = false;
btnCopy.Visibility = Visibility.Visible;
btnCopy.IsEnabled = true;
btnReset.Visibility = Visibility.Visible;
btnReset.IsEnabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The issues is could by the encoding type of the response from Google.
When you look at the Content-type of the response it isn't UTF8 always which what WebClient.DownloadStringAsync decodes it to so you have to change the decoding type
You will have to change the Webclient.Encoding to match the request type
The solution to the problem can be found here

FileUpload.SaveAs issue

I am saving (uploading) file to FTP server using file upload control and .SaveAs method. But after 1st post back session values are lost. Not sure why and any work around this.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["TheUser"] != null)
{
aUser = (clsUser)Session["TheUser"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)//continue only if the file control has the file
{
if (Get_and_Show_FileInformation())//if the file information was retrived and loaded into the textboxes
{
//continue with the execution
}
else
{
//error message displyed
}
}
}
protected bool Get_and_Show_FileInformation()
{
if (FileUpload1.HasFile)
{
string fName = FileUpload1.PostedFile.FileName;
string extension = Path.GetExtension(fName);
string FileName = fName.Substring(0, fName.Length - extension.Length);
string dir = uname;
string appPath = Server.MapPath("Uploads/") + dir;
FileInfo MyFileInfo = new FileInfo(appPath);
DirectoryInfo newDirectoryInfo = new DirectoryInfo(appPath);
if (!Directory.Exists(appPath))//if user is uploading to FTP_Upload first time, create a new directory for him/her
{
try
{
FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + dir + "/" + FileName)); // ERROR here, call to this .SaveAs method causes loss of session values (Session["TheUser"])
Image2.ImageUrl = "~/Uploads/" + dir + "/" + FileName;
return true;
}
catch (Exception ex)
{
lbl_Err.Text = "<br/>Error: Error creating and saving into your space!(Error Code:XF05)";
return false;
}
}
else
{
//same code but don't create the directory
}
}
}

I want to merge two .png images

I want to merge two .png images. but when I ga to save them there occurred an error called a generic error occurred in gdi+. I want to continue my project as soon as possible. please help me. Thanks
private void MergeImages(string ImageBack,string ImageFore)
{
try
{
System.Drawing.Graphics myGraphic = null;
Image imgB;// =new Image.FromFile(ImageBack);
imgB = Image.FromFile(ImageBack);
//FileInfo fileInfoBack = new FileInfo(ImageBack);
Image imgF;// =new Image.FromFile(ImageBack);
imgF = Image.FromFile(ImageFore);
//Bitmap tempBitmap = new Bitmap(imgB.Width, imgB.Height,imgB.PixelFormat );
// tempBitmap.Save("a"+fileInfoBack.Extension);
Image m;
m = Image.FromFile(ImageBack);
// m = Image.FromFile("a" + fileInfoBack.Extension);
myGraphic = System.Drawing.Graphics.FromImage(m);
myGraphic.DrawImageUnscaled(imgB,0,0);
myGraphic.DrawImageUnscaled(imgF,posX,posY);
myGraphic.Save();
m.Save(ImageBack.Replace(".jpg",".jpeg"),System.Drawing.Imaging.ImageFormat.Jpeg);
//m.Save(ImageBack, System.Drawing.Imaging.ImageFormat.Png);
// m.Save("d.png", System.Drawing.Imaging.ImageFormat.Png);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnFileProtector_Click(object sender, System.EventArgs e)
{
if (openFileDialog1.ShowDialog()==DialogResult.OK)
{
txtFileProtector.Text=openFileDialog1.FileName;
}
}
private void btnFilesToProtect_Click(object sender, System.EventArgs e)
{
listFilesToProtect.Items.Clear();
if (openFileDialog2.ShowDialog()==DialogResult.OK)
{
if (openFileDialog2.FileNames.Length>0)
{
for(int i=0;i<openFileDialog2.FileNames.Length;i++)
{
listFilesToProtect.Items.Add(openFileDialog2.FileNames[i]);
}
}
}
}
private void btnLoad2_Click(object sender, System.EventArgs e)
{
posX = int.Parse(textBox1.Text);
posY = int.Parse(textBox2.Text);
// heightBackImage = int.Parse(textBox3.Text);
// widthBackImage = int.Parse(textBox4.Text);
if (listFilesToProtect.Items.Count>0)
{
foreach(object it in listFilesToProtect.Items)
{
MergeImages(it.ToString(), txtFileProtector.Text);
}
}
}
You didn't show us at which line this exception is thrown, So I am going to guess here. This error usually occurs when the path of the image that you are trying to load/save is not correct, so check the path for both ImageBack and ImageFore.
Also make sure that the file you are trying to load/save to is not open by another process including your application.
It is worth to mentioned here that you should dispose the images/graphics when you finish from using them, for instance by use using. like
using(Image imgB = Image.FromFile(ImageBack))
{
//the code that is using the imgB here
}

Categories