Not Able To Use PixConverter.ToPix Leptonica C# - c#

I wanted to convert a bitmap to Leptonica.Pix.. So after I did a search I found someone who had the same problem here:
Tesseract .NET Process image from memory object
So the solution to this problem was to use PixConverter.ToPix() method.
My problem here is that I can't find this method in the latest installed Leptonica Package. I tried to remove the and reinstall the lateset version thought Nuget but the method is still not not there.
What should I do to be able to use PixConverter.ToPix()?. Thanks in advance.
EDIT: I forgot to mention that i'm using the latest Tessercat pacakge too.

You need to use the version "3.0.2" for this (PixConverter.ToPix()) to work.
So your .csproj file should have this exact match in version:
<PackageReference Include="Tesseract" Version="3.0.2" />
Hope it helps.

In Tesseract 4 there is a new way to convert this using the following syntax:
var pixFromByteArray = Pix.LoadFromMemory(byteArray);
var pixFromFile = Pix.LoadFromFile(fileName);

It lives in Tesseract namespace, more information can be found here https://github.com/charlesw/tesseract
namespace Tesseract
{
/// <summary>
/// Handles converting between different image formats supported by DotNet.
/// </summary>
public static class PixConverter
{
private static readonly BitmapToPixConverter bitmapConverter = new BitmapToPixConverter();
private static readonly PixToBitmapConverter pixConverter = new PixToBitmapConverter();
/// <summary>
/// Converts the specified <paramref name="pix"/> to a Bitmap.
/// </summary>
/// <param name="pix">The source image to be converted.</param>
/// <returns>The converted pix as a <see cref="Bitmap"/>.</returns>
public static Bitmap ToBitmap(Pix pix)
{
return pixConverter.Convert(pix);
}
/// <summary>
/// Converts the specified <paramref name="img"/> to a Pix.
/// </summary>
/// <param name="img">The source image to be converted.</param>
/// <returns>The converted bitmap image as a <see cref="Pix"/>.</returns>
public static Pix ToPix(Bitmap img)
{
return bitmapConverter.Convert(img);
}
}
}
As per the sites landing page
Add the Tesseract NuGet Package by running Install-Package Tesseract from the Package Manager Console.
Also, its worth while reading the site thoroughly.
Disclaimer, i have never used this library before, just looked up the information
Update
Just to make sure i wasn't giving you bad information, I created a new project, downloaded the latest Tesseract nuget. And was able to do the following.
using Tesseract;
...
PixConverter.ToPix()
Update2
The problem you are noticing is because you are using
https://www.nuget.org/packages/tesseract.net/
apposed to
https://www.nuget.org/packages/Tesseract/
Now 'im not sure what one you actually want. However that method dosnt not exist in the former

Related

Making port of Selenium for VFP in C#

I am trying to program a DLL in C#. This DLL should work as a kind of port for Selenium to Visual FoxPro 9 SP2. My goal is to make a DLL (or other libray type) that will work with VFP and can use Selenium. So I searched a lot (all weekend) and I found nothing. For clarification, I
found a lot of help, but none of it worked at all. I got to a point, where with regasm I managed to create .reg and .tlb files and run .reg file to create registry entry, but in VFP and function CreateObejct() [acording to some tutorials it's the only way to use .NET DLLs in VFP] it gave error "Entry point for function HelloWorld was not found" (or something similar to that, you got the idea) and same with DECLARE, which worked but function cannot be ran 'cos some issues (don't remeber excatly, something like "Class definiton cannot be found" or "Function defenition cannot be found" or "File cannot be found").
I tried everything that I found. I mainly tried to follow this tutorial: https://www.tek-tips.com/viewthread.cfm?qid=1619542 but I used a lot of other sources.
I tried:
Registering it using regsv32 (not working with C#) and with regasm
(worked but in VFP gave error)
Before registering use sn -k and then call regasm with it (not
worked at all)
Changing all settings that I found I should change (even in
combinations)
Building with all types of kinds of build settings (I think it should be x86 as 32-bit, register as COM interop = true)
Combining all above
I actually have no code, 'cos I am trying to make at least working DLL with HelloWordl() and Add() functions.
Thank you for any help
Edit:
I am going to add here some code, that I already tried:
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface INarexDLL
{
[DispId(0)]
int Add(int a, int b);
[DispId(1)]
string HelloWorld();
}
[ComSourceInterfaces(typeof(INarexDLL))]
[ClassInterface(ClassInterfaceType.AutoDual)]
[ProgId("Narex.NarexDLL")]
[ComVisible(true)]
public class Class1 : INarexDLL
{
public int Add(int a, int b)
{
return a + b;
}
public string HelloWorld()
{
return "Hello world";
}
}
And:
/// <summary>
/// Narex dll.
/// </summary>
[ComVisible(true)]
[Guid("82fb954d-378c-4e3e-9d57-2f812da564bc")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface INarexDLL
{
/// <summary>
/// Hellos the world.
/// </summary>
/// <returns>Hello World</returns>
string HelloWorld();
/// <summary>
/// Add the specified a and b.
/// </summary>
/// <returns>a + b</returns>
/// <param name="a">First number</param>
/// <param name="b">Second number</param>
int Add(int a, int b);
}
/// <summary>
/// Narex dll.
/// </summary>
[ComVisible(true)]
[Guid("bf99a6f7-4a0b-4896-813b-dbea3f75041a")]
[ClassInterface(ClassInterfaceType.AutoDual)]
[ProgId("NarexV4.NarexDLL")]
public class NarexDLL : INarexDLL
{
/// <summary>
/// Hellos the world.
/// </summary>
/// <returns>Hello World</returns>
public string HelloWorld()
{
return "Hello World from C# COM DLL";
}
/// <summary>
/// Add the specified a and b.
/// </summary>
/// <returns>a + b </returns>
/// <param name="a">First number</param>
/// <param name="b">Second number</param>
public int Add(int a, int b)
{
return a + b;
}
}
Have a look at West Wind dotnetbridge (wwdotnetbridge)
This provides robust access to net classes
(would not fit to a comment)
Looks like you don't know VFP. You might start by learning it, or as of today skip learning it and continue with C# or one of the other languages selenium has support.
VFP can use 2 types of DLL.
Win32 DLL. This is the one you meant with DECLARE. I don't think the DLL you have written in C# is a win32 DLL. These can be written in C++ and even if you want, compiled as FLL for VFP's native usage.
Activex (COM) DLL. These are the ones that we write and use in VFP using C#. For it to be usable by VFP, you must register for COM Interop.
In simple terms, you create a new class library project, be sure you are targeting x86 (VFP is 32 bits), and register for COM interop.
A sample looks like:
//...
using System.Threading.Tasks;
namespace SbcHelper
{
[ComSourceInterfaces(typeof(IcbSBCEvents))]
[ClassInterface(ClassInterfaceType.AutoDual)]
[ProgId("cbNetCOM.cbSBCx")]
[ComVisible(true)]
public class cbSBCWorker
{
#region Bulk Info
public delegate void delFeedbackProgress(SbcState state, string tableName, string message, double percentComplete);
public event delFeedbackProgress Feedbackprogress;
private List<BulkInfo> bulkInfo = new List<BulkInfo>();
private List<SbcMessage> messages;
public cbSBCWorker()
{ // ...
and would be instantiated from VFP:
oSomething = CreateObject("cbNetCOM.cbSBCx")
For registration on another computer you need to sign it and you could either do that with sn.exe (sn -k ...) or in your project settings.
Registration is NOT done using regsvr32 but regasm:
regasm yourLib.dll /codebase
You might also try using .Net libraries from VFP. If you go for it check this link:
Kodnet

<example></example> XML comment tag: how to see it?

I use Microsoft Visual Studio 2012.
When I put code examples into XML comments of C# classes/methods, I wonder: how will user that references my assemblies see that code example?
I tried to reference my own assembly, and the only way I found was: to look at assembly.xml file.
Can I settle Visual Studio or anything else to see those code examples?
Here is what I put into comments:
/// <summary>
/// This is my method example
/// </summary>
/// <example>
/// <code>
/// // Here is my code example. Call my method like this:
/// const int a = 10;
/// MethodExample(a);
/// </code>
/// </example>
public static void MethodExample(int parameter)
{
}
Here is what I get in IntelliSense:
Here is what I get in Object Browser:
Here is what I get in assembly.xml file:
What I'd like to get: see code examples in Object Browser and IntelliSense.
A number of XML comment tags appear in IntelliSense only as child elements of other tags. These tags, known as ChildCompletionList tags, are: c, code, example, list, listheader, para, paramref, see and see also.
/// <summary>
/// MethodExample the function that does it all...
/// <example>
/// <code>
/// <para/>// Here is my code example. Call my method like this:
/// <para/>const int a = 10;
/// <para/>MethodExample(a);
/// </code>
/// </example>
/// </summary>
If your not seeing XML commments in IntelliSense or they're not updating after you edit them try:
Not seeing: be sure everything is enclosed in the <summary> element.
ref: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/recommended-tags
Not updating: close & reopen solution (this seems to work pretty consistently)
VS Ent 2019 (16.10.4)

Adding Comments to Parameter in DLL

I had created a DLL in .NET ,which includes several function.Now I am suing this DLL in another App
I want that whenever the client uses my DLL,somesort of comments must be shown that shows return type,Parameters etc.like this
i see people this using XML files.Is there any alternative way?
Thanks in meekness
You need to use XML documentation specified in comments before the member declaration.
/// <summary>Some stuff here</summary>
/// <remarks>Some remarks</remarks>
/// <param name="foo">The foo to gronk</param>
Then go into your project properties and enable building an XML file alongside your library in the "Build" tab. Distribute that along with your DLL, and Visual Studio will display your content.
/// <summary>
/// This method does something.
/// </summary>
/// <param name="zain">Zain to be processed.</param>
/// <returns>True if it went okay, false otherwise.</returns>
Use /// at the start of the method declarations:
/// <summary>
/// This method does something.
/// </summary>
/// <param name="foo">Foo value to be processed.</param>
/// <returns>True if it went okay, false otherwise.</returns>
public bool DoSomething(int foo)
{
if (foo > 0)
return true;
else
return false;
}
As has been stated, you can add XML documentation at the beginning of each public member:
/// <summary>
/// This is the summary for your method.
/// </summary>
public void MyMethod()
{
/// your code here...
}
There are a host of tools to aide in the process. Check out GhostDoc for generating comments and Sandcastle for creating help files or web pages from it.

Problem in Internationalization - English DLL data is always displayed

I have a requirement where my UI should be shown in 5 different languages apart from English.
I have created two DLLs
Component.dll
Component.resources.dll
Component.resources.dll contains nothing but all the strings that are shown in the UI and a class
public class PResources
{
private static System.Resources.ResourceManager resourceMgr = new System.Resources.ResourceManager(typeof(PEditResources));
/// <summary>
/// Get NLS String method string method
/// </summary>
/// <param name="identifier"></param>
/// <returns></returns>
public static string GetNLSString(string identifier)
{
return resourceMgr.GetString(identifier, Thread.CurrentThread.CurrentUICulture);
}
/// <summary>
/// Returns the NLS Resource Mgr.
/// </summary>
/// <returns></returns>
public static System.Resources.ResourceManager GetNLSResourceMgr()
{
return resourceMgr;
}
}
In Component.dll to display the label text I use the following
label1.text = PResources.GetNLSString("IDS_LABEL1");
In English it works fine...
But when the language settings is changed to French or any other, the string displayed is still the English text.
Note: The Component.Resources.dll strings are translated in all languages.
When I debugged... I found that the GetNLSString function the Thread.Current.UICulture is French ... but the resourceMgr object is still pointing to the English .dll path and also the Thread.Current.Culture is English!
Is there any solution to this ? have I missed anything.
For every culture, you should create a folder (in the folder where the main program is) for every culture you want to support (id = two letter iso code + optional two letter region).
Inside this folder, you place the *.resources.dll, with only the strings/constants for the target culture.
Visual Studio does this automatically for you if you create an example.resx file (for the default culture) and an example.fr.resx file for French, inside the same project.

License for C# desktop application

How can I add license to my C# desktop application? I need to find a suitable free method to prevent unauthorised users installing my software.
I'm probably a bit late, but I spent a bit of time trying to work out a quick and effective method of securing a little C# application, and I would like to share my results.
It seems you can build your own, fairly secure licensing system using RSA reasonably easily.
Obviously, nothing is bullet-proof when it comes to protecting software (It's like protecting your house from burglars: alarms, barking dogs and fences make it more trouble than it's worth, but they won't stop someone determined to get in)
So, making it more trouble than it's worth is the key phrase in software protection: if you are offering a $1,000,000 E.R.P. system, you would want to have really good protection that authorized via a web-service (and users paying that much for a system would not have a problem with allowing that system constant internet access)
However, if you are charging only $5-$30 for a little app, users are not going to put up with very heavy handed authorization.
I think the simplest system to produce is to digitally sign a license-file that contains the details of product, the user and it's duration.
This means any modification of the license file makes the digital signature invalid.
The digital signature can be obtained from the DSACryptoServiceProvider class, using the SignData method.
A private key is required to sign the data, and the public part of that key can be used to validate the signature: (thus the public key must be accessible by the application)
The DSAXCryptoServiceProvider has methods for creating and using keys:
DSACryptoServiceProvider.ToXMLString(bool includePrivate);
returns the Public or Public & Private keys currently in the service provider as an XML string.
DSACryptoServiceProvider.FromXMLString(String xmlString)
This method sets up a new DSACryptoServiceProvider with existing private or public keys obtained from DSACryptoServiceProvider.ToXMLString()
The only flaw in the security of this system would be the possibility of a user breaking in an supplying their own public-key. This would allow them to generate their own license files from their own private-key.
This can be gotten around by additionally signing a required resource for the application (like a .dll that contains essential logic for the application, or even the .exe itself) - thus if the public key is changed, this additional (hidden) signature will become invalid.
Other ways to improve this include obscuring the license terms (serializing a data-structure containing the license terms using the binary-formatter to a byte array, then using Convert.ToBase64String() will quite effectively obscure the licensing terms, and even if the user was able to replace the public-key they would still need to work out the representation of the data)
I have an example system I wrote, but it is too big to quote entirely, but this is the CreateLicense method from it:
/// <summary>
/// use a private key to generate a secure license file. the private key must match the public key accessible to
/// the system validating the license.
/// </summary>
/// <param name="start">applicable start date for the license file.</param>
/// <param name="end">applicable end date for the license file</param>
/// <param name="productName">applicable product name</param>
/// <param name="userName">user-name</param>
/// <param name="privateKey">the private key (in XML form)</param>
/// <returns>secure, public license, validated with the public part of the key</returns>
public static License CreateLicense(DateTime start, DateTime end, String productName, String userName, String privateKey)
{
// create the licence terms:
LicenseTerms terms = new LicenseTerms()
{
StartDate = start,
EndDate = end,
ProductName = productName,
UserName = userName
};
// create the crypto-service provider:
DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
// setup the dsa from the private key:
dsa.FromXmlString(privateKey);
// get the byte-array of the licence terms:
byte[] license = terms.GetLicenseData();
// get the signature:
byte[] signature = dsa.SignData(license);
// now create the license object:
return new License()
{
LicenseTerms = Convert.ToBase64String(license),
Signature = Convert.ToBase64String(signature)
};
}
Verify Method:
/// <summary>
/// validate license file and return the license terms.
/// </summary>
/// <param name="license"></param>
/// <param name="publicKey"></param>
/// <returns></returns>
internal static LicenseTerms GetValidTerms(License license, String publicKey)
{
// create the crypto-service provider:
DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
// setup the provider from the public key:
dsa.FromXmlString(publicKey);
// get the license terms data:
byte[] terms = Convert.FromBase64String(license.LicenseTerms);
// get the signature data:
byte[] signature = Convert.FromBase64String(license.Signature);
// verify that the license-terms match the signature data
if (dsa.VerifyData(terms, signature))
return LicenseTerms.FromString(license.LicenseTerms);
else
throw new SecurityException("Signature Not Verified!");
}
The License Terms Class:
/// <summary>
/// terms of the license agreement: it's not encrypted (but is obscured)
/// </summary>
[Serializable]
internal class LicenseTerms
{
/// <summary>
/// start date of the license agreement.
/// </summary>
public DateTime StartDate { get; set; }
/// <summary>
/// registered user name for the license agreement.
/// </summary>
public String UserName { get; set; }
/// <summary>
/// the assembly name of the product that is licensed.
/// </summary>
public String ProductName { get; set; }
/// <summary>
/// the last date on which the software can be used on this license.
/// </summary>
public DateTime EndDate { get; set; }
/// <summary>
/// returns the license terms as an obscure (not human readable) string.
/// </summary>
/// <returns></returns>
public String GetLicenseString()
{
using (MemoryStream ms = new MemoryStream())
{
// create a binary formatter:
BinaryFormatter bnfmt = new BinaryFormatter();
// serialize the data to the memory-steam;
bnfmt.Serialize(ms, this);
// return a base64 string representation of the binary data:
return Convert.ToBase64String(ms.GetBuffer());
}
}
/// <summary>
/// returns a binary representation of the license terms.
/// </summary>
/// <returns></returns>
public byte[] GetLicenseData()
{
using (MemoryStream ms = new MemoryStream())
{
// create a binary formatter:
BinaryFormatter bnfmt = new BinaryFormatter();
// serialize the data to the memory-steam;
bnfmt.Serialize(ms, this);
// return a base64 string representation of the binary data:
return ms.GetBuffer();
}
}
/// <summary>
/// create a new license-terms object from a string-representation of the binary
/// serialization of the licence-terms.
/// </summary>
/// <param name="licenseTerms"></param>
/// <returns></returns>
internal static LicenseTerms FromString(String licenseTerms)
{
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(licenseTerms)))
{
// create a binary formatter:
BinaryFormatter bnfmt = new BinaryFormatter();
// serialize the data to the memory-steam;
object value = bnfmt.Deserialize(ms);
if (value is LicenseTerms)
return (LicenseTerms)value;
else
throw new ApplicationException("Invalid Type!");
}
}
}
There are plenty of license management systems out there for .NET (there's even one built-in for licensing controls). A quick Google around for ".NET licence manager" threw up the Open License system, which is free.
I expect you can easily find more.
I thought it would be worth adding another answer to this as the accepted answer seems to reference a project that is not currently maintained.
I would recommend looking at Standard.Licensing, which is a free, open-source licensing library for .Net that works with the .Net Framework, Mono, .Net Core, .Net Standard and Xamarin. Is modernises the older Portable.Licensing by adding support for newer platforms, specifically .Net Core and .Net Standard.
Standard.Licensing works by creating a digitally signed XML file that contains information relevant to your product, such as the type of the product and the expiry date. The fact that the XML file has not been changed can be verified when you check the licence and your application can then trust the claims made in the licence file. (Note that you might want to also verify that the computer's clock is accurate to prevent someone just changing the date.)
Standard.Licensing signs the XML file using the Elliptic Curve Digital Signature Algorithm (ECDSA) algorithm, which uses a pair of keys, one public and one private when creating the licence file. You only need to use the public key to decrypt and verify the licence. As it is not possible to use just the public key to modify the licence file, you can just safely include the public with your application and you do not need to resort to approaches such as obfuscating your assembly to prevent people from seeing the public key. Note that this is similar to the approach mentioned in Simon Bridge's answer above.
Standard.Licensing has a fluent API that you use to create and verify the licences. Here's the snippet from their website showing how to create a licence:
var license = License.New()
.WithUniqueIdentifier(Guid.NewGuid())
.As(LicenseType.Trial)
.ExpiresAt(DateTime.Now.AddDays(30))
.WithMaximumUtilization(5)
.WithProductFeatures(new Dictionary<string, string>
{
{"Sales Module", "yes"},
{"Purchase Module", "yes"},
{"Maximum Transactions", "10000"}
})
.LicensedTo("John Doe", "john.doe#example.com")
.CreateAndSignWithPrivateKey(privateKey, passPhrase);
In your application, you then load and validate the licence file:
using Standard.Licensing.Validation;
var license = License.Load(...);
var validationFailures = license.Validate()
.ExpirationDate()
.When(lic => lic.Type == LicenseType.Trial)
.And()
.Signature(publicKey)
.AssertValidLicense();
Technically, its not easy task to create working and secure licensing system. In case you plan to develop commercial software, I would recommend to use some commercial solution for it. Custom coded licensing systems tend to be vulnerable.
I have best experience with Treek's Licensing Library. Its cheap even for single developer, its safe and with good support. When comparing costs, TLL is cheaper than renting your own developer to do the same job.
Also, you'll need to protect your sources. For that we do use EAZ Fuscator, but there are also free options available. EAZ is very good, but very expensive.
One approach is to roll your own partial key verification system. There is a VB.NET version available on Code Project:
http://www.codeproject.com/KB/security/cdkeys.aspx
Be wary of how much effort you put in to protecting your app; it may be wasted time if it is easily broken or off putting to users if very strong (e.g. having to enter a password every time it is run).
An interesting article on software protection (of games) can be found here:
http://www.positech.co.uk/talkingtopirates.html

Categories