Emgu CV C# Exception creating tesseract object - c#-4.0

I can access all emgu libraries. VS finds the libraries and using Emgu.CV.OCR returns no errors.
When I try to create a Tesseract object, Program.cs throws a FileLoadException. in System.Windows.Forms.dll.
Removing the line of code that creates a tesseract lets the program run fine.
I have tried copying tessdata to my debug file and that also has not worked.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
Tesseract _ocr;
_ocr = new Tesseract(#"tessdata", "eng", Tesseract.OcrEngineMode.OEM_TESSERACT_CUBE_COMBINED);
OpenFileDialog Openfile = new OpenFileDialog();
if (Openfile.ShowDialog() == DialogResult.OK)
{
Image<Bgr, Byte> My_Image = new Image<Bgr, byte>(Openfile.FileName);
pictureBox1.Image = My_Image.ToBitmap();
}
}

I fiddled with the same problem for a while; now I got it.
First, make sure you have the following using directives (you might need to download Emgu.CV via NuGet):
using Emgu.CV;
using Emgu.CV.OCR;
using System.Reflection;
using System.IO;
using System.Drawing;
Then, make sure you have the most up-to-date tessdata on board. If not, navigate to github and download it (click "Clone or Download" and select "Download ZIP File"). You should then unzip the file and rename the folder "tessdata-master" to "tessdata." Copy this folder to the place where your binary lives (the assembly location).
Lastly, assign the correct path, and you're ready to do OCR!
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\";
var _ocr = new Tesseract(path, "eng", OcrEngineMode.Default);
_ocr.SetImage(yourImage);
_ocr.Recognize();
var result = _ocr.GetCharacters();

First you need to check your project References . Is there "Emgu.CV.OCR" library if not kindly add it first. Then try the following code may it will work for you.
private void button1_Click(object sender, EventArgs e)
{
Tesseract _ocr;
_ocr = new Tesseract(#"C:\Emgu\emgucv-windows-universal-cuda 2.9.0.1922\Emgu.CV.OCR\tessdata", "eng", Tesseract.OcrEngineMode.OEM_TESSERACT_CUBE_COMBINED);//first Parameter set your path ..complete path like i did
_ocr.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopkrstuvwxyz");
OpenFileDialog Openfile = new OpenFileDialog();
if (Openfile.ShowDialog() == DialogResult.OK)
{
Image<Bgr, Byte> My_Image = new Image<Bgr, byte>(Openfile.FileName);
pictureBox1.Image = My_Image.ToBitmap();
}
}

Related

File path working in NetBeans but not in built JAR file

I am trying to copy file from classpath to user specified location. However, While running program in netbeans, file path works correctly and file gets copied but when I build a jar file and try the same, it doesnt locates source file.
URL url = getClass().getResource("utils/mount");
File file = new File(url.getPath());
this.copyEachFile(url.getPath(), "C:\\Users\\Nikhil\\Desktop\\" + mount); //this function takes in source path of file and copies it to destination path.
when I trace source path I get
/C:/Users/Nikhil/Documents/NetBeansProjects/Aroma-Installer/build/classes/aroma/installer/utils/mount
in netbeans and following in jar
/C:/Users/Nikhil/Documents/NetBeansProjects/Aroma-Installer/dist/Aroma-Installer.jar!/aroma/installer/utils/mount
When I run program in netbeans, file successfully copies but while running through jar, it says source doesnt exist.
Where is the problem?
Okay so I created a function and called it as follows.
this.copyFileFromJar("utils/mount", "C:\\Users\\Nikhil\\Desktop\\mount");
Definition of function is as follows.
public void copyFileFromJar(String source, String destination) throws IOException{
File dest = new File(destination);
if(!dest.exists()){
dest.createNewFile();
}
InputStream in = null;
OutputStream out = null;
try{
in = this.getClass().getResourceAsStream(source); //Important step, it returns InputStream which can be manipulated as per need.
out = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int len;
while((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
JOptionPane.showMessageDialog(null, "File Successfully copied at" + dest.getAbsolutePath());
System.out.println("File Writing......" + dest.getName());
}
finally{
in.close();
out.close();
}
}
And now I am able to copy files from jar file to user specified location.
Hope this helps anybody who is looking for same kind of problem.

Downloading bulk files from sharepoint library

I want to download the files from a sharepoint document library through code as there are thousand of files in the document library.
I am thinking of creating console application, which I will run on sharepoint server and download files. Is this approach correct or, there is some other efficient way to do this.
Any help with code will be highly appreciated.
Like SigarDave said, it's perfectly possible to achieve this without writing a single line of code. But if you really want to code the solution for this, it's something like:
static void Main(string[] args)
{
// Change to the URL of your site
using (var site = new SPSite("http://MySite"))
using (var web = site.OpenWeb())
{
var list = web.Lists["MyDocumentLibrary"]; // Get the library
foreach (SPListItem item in list.Items)
{
if (item.File != null)
{
// Concat strings to get the absolute URL
// to pass to an WebClient object.
var fileUrl = string.Format("{0}/{1}", site.Url, item.File.Url);
var result = DownloadFile(fileUrl, "C:\\FilesFromMyLibrary\\", item.File.Name);
Console.WriteLine(result ? "Downloaded \"{0}\"" : "Error on \"{0}\"", item.File.Name);
}
}
}
Console.ReadKey();
}
private static bool DownloadFile(string url, string dest, string fileName)
{
var client = new WebClient();
// Change the credentials to the user that has the necessary permissions on the
// library
client.Credentials = new NetworkCredential("Username", "Password", "Domain");
var bytes = client.DownloadData(url);
try
{
using (var file = File.Create(dest + fileName))
{
file.Write(bytes, 0, bytes.Length); // Write file to disk
return true;
}
}
catch (Exception)
{
return false;
}
}
another way without using any scripts is by opening the document library using IE then in the ribbon you can click on Open in File Explorer where you can then drag and drop the files right on your desktop!

Path Manipulation while creating shortcut in C#

Using below code i am creating a shortcut.When i do run HP fortify tool i am getting path manipulation issues for the highlighted code.I am new to this.Can anyone please tell me how to correct it.I mean what path manipulation is happening.
string fileName = new data().getdata(object_id, Cid, id_pluf).Tables[0].Rows[0]["Name"] + "url";
**var fs = new System.IO.FileStream(start + fileName, System.IO.FileMode.Create);**
fs.Write(bytes, 0, bytes.Length);
fs.Flush();
fs.Close();
private static void DeleteShortcut(string start, string fileName)
{
**if (System.IO.File.Exists(start+ fileName))**
{
**System.IO.File.Delete(start+ fileName);**
}
}
Always use :
Path.Combine(start, fileName)
instead of :
start+ fileName

How to zip and unzip folders and its sub folders in Silverlight?

I have a Windows Phone application. I am using SharpZipLib to zip folders and its sub folders. This is zipping only the folder but the data inside the folders is not getting zipped. Can anyone guide me how to do this?
My code:
private void btnZip_Click(object sender, RoutedEventArgs e)
{
using (IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication())
{
foreach (string filename in appStore.GetFileNames(directoryName + "/" + "*.txt"))
{
GetCompressedByteArray(filename);
}
textBlock2.Text = "Created file has Zipped Successfully";
}
}
public byte[] GetCompressedByteArray(string content)
{
byte[] compressedResult;
using (MemoryStream zippedMemoryStream = new MemoryStream())
{
using (ZipOutputStream zipOutputStream = new ZipOutputStream(zippedMemoryStream))
{
zipOutputStream.SetLevel(9);
byte[] buffer;
using (MemoryStream file = new MemoryStream(Encoding.UTF8.GetBytes(content)))
{
buffer = new byte[file.Length];
file.Read(buffer, 0, buffer.Length);
}
ZipEntry entry = new ZipEntry(content);
zipOutputStream.PutNextEntry(entry);
zipOutputStream.Write(buffer, 0, buffer.Length);
zipOutputStream.Finish();
}
compressedResult = zippedMemoryStream.ToArray();
}
WriteToIsolatedStorage(compressedResult);
return compressedResult;
}
public void WriteToIsolatedStorage(byte[] compressedBytes)
{
IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication();
appStore.CreateDirectory(ZipFolder);
using (IsolatedStorageFileStream zipTemplateStream = new IsolatedStorageFileStream(ZipFolder+"/"+directoryName + ".zip", FileMode.OpenOrCreate, appStore))
using (BinaryWriter streamWriter = new BinaryWriter(zipTemplateStream))
{
streamWriter.Write(compressedBytes);
}
}
I think you'll find this guide helpful.
An excerpt from the above link
The ZipFile object provides a method called AddDirectory() that
accepts a parameter directoryName. The problem with this method is
that it doesn't add the files inside the specified directory but
instead just creates a directory inside the zip file. To make this
work, you need to get the files inside that directory by looping thru
all objects in that directory and adding them one at a time. I was
able to accomplish this task by creating a recursive function that
drills through the whole directory structure of the folder you want to
zip. Below is a snippet of the function.
I guess you too are facing the same problem where the folder is added to the zip file, but the contents and sub folders are not zipped.
Hope this helps.
Have a look over here for a code sample on how to use SharpZipLib to zip a root folder including nested folders.

Dynamically add mergefields in existing docx-document

Is it possible to add mergefields to an existing .docx document without using interop, only handling with open SDK from CodeBehind?
Yes this is possible, I've created a little method below where you simply pass through the name you want to assign to the merge field and it creates it for you.
The code below is for creating a new document but it should be easy enough to use the method to append to an existing document, hope this helps you:
using System;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using (WordprocessingDocument package = WordprocessingDocument.Create("D:\\ManualMergeFields.docx", WordprocessingDocumentType.Document))
{
package.AddMainDocumentPart();
Paragraph nameMergeField = CreateMergeField("Name");
Paragraph surnameMergeField = CreateMergeField("Surname");
Body body = new Body();
body.Append(nameMergeField);
body.Append(surnameMergeField);
package.MainDocumentPart.Document = new Document(new Body(body));
}
}
static Paragraph CreateMergeField(string name)
{
if (!String.IsNullOrEmpty(name))
{
string instructionText = String.Format(" MERGEFIELD {0} \\* MERGEFORMAT", name);
SimpleField simpleField1 = new SimpleField() { Instruction = instructionText };
Run run1 = new Run();
RunProperties runProperties1 = new RunProperties();
NoProof noProof1 = new NoProof();
runProperties1.Append(noProof1);
Text text1 = new Text();
text1.Text = String.Format("«{0}»", name);
run1.Append(runProperties1);
run1.Append(text1);
simpleField1.Append(run1);
Paragraph paragraph = new Paragraph();
paragraph.Append(new OpenXmlElement[] { simpleField1 });
return paragraph;
}
else return null;
}
}
}
You can download the Open Xml Productivity Tool from this url(if you do not already have it)http://www.microsoft.com/download/en/details.aspx?id=5124
This tool has a "Reflect Code" functionality.So you can manually create a merge field in an MS Word document and then open up the document with the Productivity Tool
and see a C# code sample on how to do this in code!It's very effective an I've used this exact tool to create the sample above.Good luck

Resources