Document Scanning from ASP.net Web Application - asp.net

I have a ASP.Net C# 4.0 Web Application
I need to Add a scanning feature for my users.
This is what I want to achieve
On my web application
user clicks on a button
opens a window with preview of document in Scanning device attached to the client system
User confirms the Scan
this will save the Scanned document in jpg/pdf format on the server
then do the OCR on document
Can any one suggest a way to achieve this.
I read about this https://www.leadtools.com/sdk/engine/imaging not sure how much this can work. Can any one suggest a best way to get this done.
Thanks
update
tried leadtools from https://www.leadtools.com/support/forum/posts/m28036-Re--Scan-and-Upload-v16--NET-with-Caspol-exe-deployment as LEAD Support suggested but it is missing references not sure where and how to get those references

HaBo,
This is LEAD support. Since you mentioned our LEADTOOLS toolkit, the answer to your question is yes. Our toolkit can be used to implement either of the 2 approaches mentioned by tgolisch.
For the click-once approach, you simply use our Windows Forms controls that contain Twain support and package your application for ClickOnce deployment. This is done, for example, in this demo project:
LEADTOOLS ClickOnce Demos
For the custom control approach, see the example code projects on our forums that perform Scan and Upload

Solution is here:
In ASP.Net/Core Project you send message to call winform project:
var start = function () {
var i = 0;
var wsImpl = window.WebSocket || window.MozWebSocket;
window.ws = new wsImpl('ws://localhost:8181/');
ws.onmessage = function (e) {
$('#submit').hide();
$('#scanBtn').hide();
$('.loader').show();
if (typeof e.data === "string") {
//IF Received Data is String
}
else if (e.data instanceof ArrayBuffer) {
//IF Received Data is ArrayBuffer
}
else if (e.data instanceof Blob) {
i++;
var f = e.data;
f.name = "File" + i;
storedFiles.push(f);
formdata.append(f.name, f);
var reader = new FileReader();
reader.onload = function (e) {
var html = "<div class=\"col-sm-2 text-center\"
style=\"border: 1px solid black; margin-left: 2px;\"><img
height=\"200px\" width=\"200px\" src=\"" + e.target.result + "\"
data-file='" + f.name + "' class='selFile' title='Click to
remove'><br/>" + i + "</div>";
selDiv.append(html);
$('#submit').show();
$('#scanBtn').show();
$('.loader').hide();
}
reader.readAsDataURL(f);
}
};
ws.onopen = function () {
//Do whatever u want when connected succesfully
};
ws.onclose = function () {
$('.dalert').modal('show');
};
}
window.onload = start;
function scanImage() {
ws.send("1100");
};
https://javascript.info/websocket
In Winforms Project you scan document and send graphic data back to Asp.Net/Core project:
public partial class Form1 : Form
{
ImageCodecInfo _tiffCodecInfo;
TwainSession _twain;
bool _stopScan;
bool _loadingCaps;
List allSockets;
WebSocketServer server;
public Form1()
{
InitializeComponent();
if (NTwain.PlatformInfo.Current.IsApp64Bit)
{
Text = Text + " (64bit)";
}
else
{
Text = Text + " (32bit)";
}
foreach (var enc in ImageCodecInfo.GetImageEncoders())
{
if (enc.MimeType == "image/tiff") { _tiffCodecInfo = enc; break; }
}
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
allSockets = new List<IWebSocketConnection>();
server = new WebSocketServer("ws://0.0.0.0:8181");
server.Start(socket =>
{
socket.OnOpen = () =>
{
Console.WriteLine("Open!");
allSockets.Add(socket);
};
socket.OnClose = () =>
{
Console.WriteLine("Close!");
allSockets.Remove(socket);
};
socket.OnMessage = message =>
{
if (message == "1100")
{
this.Invoke(new Action(()=> {
this.WindowState = FormWindowState.Normal;
}));
}
};
});
}
Link to project.
https://github.com/mgriit/ScanAppForWeb
You can remake this project, as you want.

Web browsers don't have permissions to use system devices like this(major security issue). There are 2 common ways of getting around this:
Make a custom control to run in your browser (flash, silverlight, java applet).
Make a "click-once deployment app" that a user launches from your page.
Both approaches would send the data back to your server via web
services or WCF, etc.

Related

send notification from background worker

am using ABP to build my project
I have a module to generate big size files using background worker, and after each successful file generated I need to send notification, but is not working !
I've put the background job in the core project and the queue in the engine project,
the DB notification tables are updated successfully (new record inserted so the pull notification will work fine !), but the browser doesn't receive the notification (so I can inform him that his file is ready), but there is no errors and no any notification send to the browser.
here is the worker class:
public class GeneratedFileWorker : BackgroundWorkerBase, ISingletonDependency
{
.
.
.
[UnitOfWork]
[AutomaticRetry(Attempts = 0)]
public override async System.Threading.Tasks.Task ExecuteAsync()
{
var notificationData = new NotificationData();
notificationData["URL"] = "app/main/data/generatedfiles";
using (AbpSession.Use(TenantConsts.DefaultTenantId, TenantConsts.UserServiceId))
{
GetDownloadArticleInput getDownloadArticleInput = new GetDownloadArticleInput();
if (pendingRequest is not null)
{
var entityType = _lookupItemManager.Get(pendingRequest.EntityTypeId).Code;
dynamic Args = JsonConvert.DeserializeObject<GetDownloadArticleInput>(String.Empty);
switch (entityType)
{
case "Article":
Args = JsonConvert.DeserializeObject<GetDownloadArticleInput>(pendingRequest.ExtensionData);
break;
case "ArticlesList":
Args = JsonConvert.DeserializeObject<GetDownloadArticlesInput>(pendingRequest.ExtensionData);
break;
};
GeneratedFile generatedFileDto = new GeneratedFile();
try
{
generatedFileDto = await _generateFile.Generate(Args);
await _appNotifier.SendMessageAsync(new UserIdentifier(1, pendingRequest.CreatorUserId.Value),string.Format(_LocalizationSource.GetString("GeneratedFile.fileIsNotready"), _lookupItemManager.GetTitle(pendingRequest.EntityTypeId)), notificationData, NotificationSeverity.Error);
else
await _appNotifier.SendMessageAsync(new UserIdentifier(1, pendingRequest.CreatorUserId.Value), string.Format(_LocalizationSource.GetString("GeneratedFile.fileIsready"), _lookupItemManager.GetTitle(pendingRequest.EntityTypeId)), notificationData, NotificationSeverity.Success);
}
catch (Exception ex)
{
pendingRequest.CurrentStateId = _lookupItemManager.GetByCode(LookupCategories.GeneratedFileStatus, "Failed").Id;
pendingRequest.OperationResult = ex.ToString();
await _generatedFileRepository.UpdateAsync(pendingRequest);
await _appNotifier.SendMessageAsync(new UserIdentifier(1, pendingRequest.CreatorUserId.Value), string.Format(_LocalizationSource.GetString("GeneratedFile.fileIsNotready"), _lookupItemManager.GetTitle(pendingRequest.EntityTypeId)), notificationData, NotificationSeverity.Error);
}
}
}
}
I have 2 cases here:
first one working when I define the queue in the host project, and
second one not working when I define the queue in the engine project

Can we use Web API such as new CSSStyleSheet() while vs code extension development?

Can we use web API while development of a vs code extension ?
I was trying to do something like below
let activeEditor = vscode.window.activeTextEditor;
function replaceWithinDocument() {
if (!activeEditor) {
return;
}
const { document } = activeEditor;
const text = document.getText();
//console.log({ text })
const stylesheet = new CSSStyleSheet();
// Add some CSS
stylesheet.replaceSync(text);
}
but it throw error of because of new CSSStyleSheet()
so can't we use or is there any other way to write it ?

How to post Special character tweet using asp.net API?

I m using Given below code to post the tweet on twitter. But when we upload it on the server then special character (!,:,$ etc) tweets not published on twitter. this code is working fine in the local system
string key = "";
string secret = "";
string token="";
string tokenSecret="";
try
{
string localFilename = HttpContext.Current.Server.MapPath("../images/").ToString();
using (WebClient client = new WebClient())
{
client.DownloadFile(imagePath, localFilename);
}
var service = new TweetSharp.TwitterService(key, secret);
service.AuthenticateWith(token, tokenSecret);
// Tweet wtih image
if (imagePath.Length > 0)
{
using (var stream = new FileStream(localFilename, FileMode.Open))
{
var result = service.SendTweetWithMedia(new SendTweetWithMediaOptions
{
Status = message,
Images = new Dictionary<string, Stream> { { "name", stream } }
});
}
}
else // just message
{
var result = service.SendTweet(new SendTweetOptions
{
Status = HttpUtility.UrlEncode(message)
});
}
}
catch (Exception ex)
{
throw ex;
}
The statuses/update_with_media API endpoint is actually deprecated by Twitter and shouldn't be used (https://dev.twitter.com/rest/reference/post/statuses/update_with_media).
TweetSharp also has some issues with using this method when the tweet contains both a 'special character' AND an image (works fine with either, but not both). I don't know why and I haven't been able to fix it, it's something to do with the OAuth signature I'm pretty sure.
As a solution I suggest you use TweetMoaSharp (a fork of TweetSharp). It has been updated to support the new Twitter API's for handling media in tweets, and it will work in this situation if you use the new stuff.
Basically you upload each media item using a new UploadMedia method, and that will return you a 'media id'. You then use the normal 'SendTweet' method and provide a list of the media ids to it along with the other status details. Twitter will attach the media to the tweet when it is posted, and it will work when there are both special characters and images.
In addition to TweetMoaSharp you can use Tweetinvi with the following code:
var binary = File.ReadAllBytes(#"C:\videos\image.jpg");
var media = Upload.UploadMedia(binary);
var tweet = Tweet.PublishTweet("hello", new PublishTweetOptionalParameters
{
Medias = {media}
});

Http Passthrough Pluggable Protocol for Firefox

How can I make an http passthrough pluggable protocol for IE work in Firefox?
Alternatively, how to develop one for Firefox? Any examples would be appreciated.
Thanks.
On Firefox, if you would like to bypass a default behavior in a "pluggable" manner, you could write an NPAPI based plugin. Let's say that the documentation is thin on this subject... but to get you started, you could consult this.
With an NPAPI plugin, you have access to the whole OS and thus are free to expose any other resources to Firefox.
Write an XPCOM object that implements nsIObserver. Then create listener for http-on-modify-request and http-on-examine-response.
var myObj = new MyObserver(); //implements nsIObserver
var observerService = Components.classes["#mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
observerService.addObserver(myObj "http-on-modify-request", false);
observerService.addObserver(myObj, "http-on-examine-response", false);
Write an XPCOM object that implements nsIProtocolHandler. For example, you can access local images from web pages:
const Cu = Components.utils;
const Ci = Components.interfaces;
const Cm = Components.manager;
const Cc = Components.classes;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");+
Cu.import("resource://gre/modules/FileUtils.jsm");
Cu.import("resource://gre/modules/NetUtil.jsm");
/***********************************************************
class definition
***********************************************************/
function sampleProtocol() {
// If you only need to access your component from JavaScript,
//uncomment the following line:
this.wrappedJSObject = this;
}
sampleProtocol.prototype = {
classDescription: "LocalFile sample protocol",
classID: Components.ID("{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"),
contractID: "#mozilla.org/network/protocol;1?name=x-localfile",
QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolHandler]),
//interface nsIProtocolHandler
allowPort :function(port, scheme)
{
if ((port == 80)&&(scheme == x-localfile)) {
return true;
}
else
{
return false;
}
},
newChannel: function(aURI)
{
// Just example. Implementation must parse aURI
var file = new FileUtils.File("D:\\temp\\getImage.jpg");
var uri = NetUtil.ioService.newFileURI(file);
var channel = NetUtil.ioService.newChannelFromURI(uri);
return channel;
},
newURI(aSpec, aOriginCharset, aBaseURI)
{
//URI looks like x-localfile://example.com/image1.jpg
var uri = Cc["#mozilla.org/network/simple-uri;1"].createInstance(Ci.nsIURI);
uri.spec = aSpec;
return uri;
},
scheme: "x-localfile",
defaultPort: 80,
protocolFlags: 76
};
var components = [sampleProtocol];
if ("generateNSGetFactory" in XPCOMUtils)
var NSGetFactory = XPCOMUtils.generateNSGetFactory(components); // Firefox 4.0 and higher
else
var NSGetModule = XPCOMUtils.generateNSGetModule(components); // Firefox 3.x
Be carefull! This approach can create vulnerability

JSON WebService in ASP.NET

How do I create an ASP.NET web service that returns JSON formatted data?
The most important thing to understand is to know how to represent data in JSON format.
Please refer http://www.json.org/ to know more about it.
Once you understand this, then the rest part is pretty straight forward.
Please check the following URL for an example of the same.
http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=264
http://code.msdn.microsoft.com/JSONSampleDotNet
http://www.phdcc.com/xml2json.htm
I recommend Jquery library for this. It's a lightweight rich library which supports calling web services, handle json data format output etc.
Refer www.jquery.com for more info.
.NET 3.5 has support built-in. For .NET 2.0, extra libraries are needed. I used the Jayrock library.
I recently delivered an application that uses pure Javascript at the browser (viz. using AJAX technology, but not using Microsoft AJAX or Scriptaculous etc) which marries up to Microsoft webservices at the back end. When I started writing this I was new to the world of .NET, and felt overwhelmed by all the frameworks out there! So I had an urge to use a collection of small libraries rather than very large frameworks.
At the javascript application, I call a web service like this. It directly reads the output of the web service, cuts away the non JSON sections, then uses https://github.com/douglascrockford/JSON-js/blob/master/json2.js to parse the JSON object.
This is not a standard approach, but is quite simple to understand, and may be of value to you, either to use or just to learn about webservices and JSON.
// enclosing html page has loaded this:
<script type="text/javascript" src="res/js/json2.js"></script>
// Invoke like this:
// var validObj = = callAnyWebservice("WebServiceName", "");
// if (!validObj || validObj.returnCode != 0) {
// alert("Document number " + DocId + " is not in the vPage database. Cannot continue.");
// DocId = null;
// }
function callAnyWebservice(webserviceName, params) {
var base = document.location.href;
if (base.indexOf(globals.testingIPaddr) < 0) return;
gDocPagesObject=null;
var http = new XMLHttpRequest();
var url = "http://mywebserver/appdir/WebServices.asmx/" + webserviceName;
//alert(url + " " + params);
http.open("POST", url, false);
http.setRequestHeader("Host", globals.testingIPaddr);
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http.setRequestHeader("Content-Length", params.length);
// http.setRequestHeader("Connection", "close");
//Call a function when the state changes.
http.onreadystatechange = function() {
if (http.readyState == 4 ) {
if (http.status == 200) {
var JSON_text = http.responseText;
var firstCurlyQuote = JSON_text.indexOf('{');
JSON_text = JSON_text.substr(firstCurlyQuote);
var lastCurlyQuote = JSON_text.lastIndexOf('}') + 1;
JSON_text = JSON_text.substr(0, lastCurlyQuote);
if (JSON_text!="")
{
//if (DEBUG)
// alert(url+" " +JSON_text);
gDocPagesObject = eval("(" + JSON_text + ")");
}
}
else if (http.readyState == 4)
{alert(http.readyState + " " + http.status + " " + http.responseText)}
}
}
http.send(params);
if (gDocPagesObject != null) {
//alert(gDocPagesObject.returnCode + " " + gDocPagesObject.returnString);
return gDocPagesObject;
}
else
return "web service unavailable: data not ready";
}
In our project the requirements were as follow -- ASP.NET 2.0 on the server, and pure Javascript on the browser (no JQuery libs, or .NET AJAX)
In that case on the server side, just mark the webmethod to use JSON. Note that both input and output params are json formatted
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public String Foo(String p1, String p2)
{
return "Result: p1= " + p1 + " p2= " + p2;
}
On the javascript side, use the regular XmlHttpRequest object, make sure you format your input params as JSON and do an 'eval' on output parms.
var httpobj = getXmlHttpRequestObject();
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject()
{
if (window.XMLHttpRequest)
return new XMLHttpRequest();
else if(window.ActiveXObject)
return new ActiveXObject("Microsoft.XMLHTTP");
}
CallService()
{
//Set the JSON formatted input params
var param = "{'p1' : 'value1', 'p2' : 'value2'}";
//Send it to webservice
if(httpobj.readyState == 4 || httpobj.readyState == 0)
{
httpobj.open("POST", 'service.asmx/' + 'Foo', true);
//Mark the request as JSON and UTF-8
httpobj.setRequestHeader('Content-Type','application/json; charset=utf-8');
httpobj.onreadystatechange = OnSuccess;
httpobj.send(param);
}
}
OnSuccess()
{
if (httpobj.readyState == 4)
{
//Retrieve the JSON return param
var response = eval("(" + httpobj.responseText + ")");
}
}

Resources