WIA silverlight Scanner integration - silverlight

I am new to silverlight , and I am experimenting with wia scanner integration. I know usng WIA.CommonDialog , showacquireimage() I can retrieve an image from the scanner. I am trying to access the device directly and execute the scan command to avoid user interaction.
I am able to connect to the device. But the only command available from the scanner is synchronize. I am trying to use the ExecuteCommand on the device object, but I am not sure what command to use. Any direction will be appreciated.
using (dynamic DeviceManager1 = AutomationFactory.CreateObject("WIA.DeviceManager"))
{
var deviceInfos = DeviceManager1.DeviceInfos;
for(int i= 1;i<=deviceInfos.Count;i++)
{
//check if the device is a scanner
if (deviceInfos.Item(i).Type.ToString() == "1")
{
var IDevice = deviceInfos.Item(i).Connect();
deviceN.Text = IDevice.Properties("Name").Value.ToString();
var dv = IDevice.Commands;
for (int j = 0; j <= dv.Count; j++)
{
deviceN.Text += " " + dv.Item(i).CommandID.ToString() + " " + dv.Item(i).Description.ToString();
}
}
}
}

You don't really need to deal with the device commands to scan the document. Instead you need to use the first device item under the device object. Here is a little example which works in itself, without failure checks for easier readability.
//using WIA;
bool showProgressBar = false;
DeviceManager deviceManager = new DeviceManagerClass();
foreach(DeviceInfo info in deviceManager.DeviceInfos)
{
if(info.Type == WiaDeviceType.ScannerDeviceType)
{
Device device = info.Connect();
ImageFile imageFile = null;
Item deviceItem = null;
//Read through the list of items under the device...
foreach(Item item in device.Items)
{
//Pick the very first one!
deviceItem = item;
break;
}
if(showProgressBar == true)
{
//Scan without GUI, but display the progress bar dialog.
CommonDialogClass commonDialog = new CommonDialogClass();
imageFile = (ImageFile)commonDialog.ShowTransfer(deviceItem, FormatID.wiaFormatBMP, false);
}
else
{
//Scan without GUI, no progress bar displayed...
imageFile = (ImageFile)deviceItem.Transfer(FormatID.wiaFormatBMP);
}
imageFile.SaveFile("C:\\image.bmp");
}
}
Before scanning (but after you connected to the device item), you probably need to set various device properties to select the scanning resolution, color depth and other things if the defaults are not good enough for your needs.
Not long ago I made an easy to use class to operate WIA-compatible scanners, you can download it from this page... It's for .Net Framework 2.0, C#. Maybe it could come handy in your project, you would be done with a few lines of code including setting the basic properties. :)

Related

Prevent Code Behind from loading Facebook Pixel Code again if it is already loaded on the Front End?

My module needs to submit a Complete Registration Facebook Pixel Event when a registration has been completed.
On the Facebook Pixel Helper tool, it says that the Pixel Code loaded twice.
Sometimes it doesn't.
I have got the Pixel tracking code on all the Skin files in DNN.
Sometimes a post-back happens and I need to load it again in the Code-Behind when the "Registration Successful" message loads along with the Facebook Tracking Event.
What can I add to the IF statement below to check if the Facebook Pixel code hasn't already loaded on the Front End?
This is my code:
RegUserFacebookPixelID = TryGetPortalSetting("FacebookPixelID");
if (RegUserFacebookPixelID != null)
{
string FacebookPixelResult = string.Empty;
using (var FBPxl = new StringWriter())
using (var FBCodescript = new HtmlTextWriter(FBPxl))
{
FBCodescript.AddAttribute(Attr.Type, "text/javascript");
FBCodescript.RenderBeginTag(Tag.Script);
//load ecommerce plugin
FBCodescript.WriteLine("!function(f,b,e,v,n,t,s){if (f.fbq) return; n = f.fbq = function(){n.callMethod?n.callMethod.apply(n, arguments):n.queue.push(arguments)};");
FBCodescript.WriteLine("if (!f._fbq) f._fbq = n; n.push = n; n.loaded = !0; n.version = '2.0';");
FBCodescript.WriteLine("n.queue =[]; t = b.createElement(e); t.async = !0;");
FBCodescript.WriteLine("t.src = v; s = b.getElementsByTagName(e)[0];");
FBCodescript.WriteLine("s.parentNode.insertBefore(t, s)}");
FBCodescript.WriteLine("(window, document,'script','https://connect.facebook.net/en_US/fbevents.js');");
FBCodescript.RenderEndTag();
FBCodescript.WriteLine($"<noscript><img height='1' width='1' style='display:none' src='https://www.facebook.com/tr?id={RegUserFacebookPixelID}&ev=PageView&noscript=1'/></noscript>");
FacebookPixelResult = FBCodescript.InnerWriter.ToString();
}
Page.ClientScript.RegisterStartupScript(this.GetType(), "myFacebookPixelInitialization", FacebookPixelResult, false);
}

Attach a PDF File to a Print Dialog

I'm trying to attach a PDF File to a Print Dialog, but I haven't find out the way to do it.
I'm using a WPF app, and I have some code related with printing and looks like this:
private void Imprimir()
{
try
{
FixedDocument document = null;
PageContent pageContent = null;
FixedPage fixedPage = null;
PrintDialog printDlg = new PrintDialog();
if (printDlg.ShowDialog() != true)
return;
document.DocumentPaginator.PageSize = new System.Windows.Size(1400, 1450);
fixedPage.Width = document.DocumentPaginator.PageSize.Width;
fixedPage.Height = document.DocumentPaginator.PageSize.Height;
fixedPage.Margin = new Thickness(96, 96, 0, 0);
fixedPage.Children.Add(this);
((System.Windows.Markup.IAddChild)pageContent).AddChild(fixedPage);
document.Pages.Add(pageContent);
printDlg.PrintDocument(document.DocumentPaginator, "Impresion Cierre");
fixedPage.Children.Clear();
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
}
But, by this way I'm just printing a UI Element added to Fixed Page.
I've looked for other codes, but I find nothing.
So, I donĀ“t know if is possible to add a PDF File stored locally to the Print Dialog ?
Thanks for the help...
Well you cannot do this using PrintDialog. There are several options, depending on your goals:
var printQueue = LocalPrintServer.GetDefaultPrintQueue();
using (var input = File.OpenRead("path_to_your.pdf")) {
using (var job = printQueue.AddJob()) {
using (var output = job.JobStream) {
input.CopyTo(output);
}
}
}
Will silently send print job for your file to local print queue. Print job is configurable.
Alternatively you can use adobe reader to handle that for you (or another pdf reader installed on user's machine) but starting process with path to your pdf as FileName and Verb="print".
One more option is to use third party tools (like ghostscript) which can help you with that.

SharpDX.WPF Increasing memory usage during rendering

I have started working with DirectX in WPF app. My first step was to use simple library:
SharpdDX.WPF. Based on samples I've implemented WPF control drawing simple line. SharpDX.WPF uses D3DImage to render images in WPF.
Unfortunately application's memory increasing all time.
I implemented class TestControlRenderer : D3D10.
Vertex shader is initialized like:
var sizeInBytes = dataLength * sizeof(int) * 3;
var bufferDescription = new BufferDescription(
sizeInBytes,
ResourceUsage.Dynamic,
BindFlags.VertexBuffer,
CpuAccessFlags.Write,
ResourceOptionFlags.None);
using (var stream = new DataStream(sizeInBytes, true, true))
{
stream.Position = 0;
_graphDataVertexBuffer = new SharpDX.Direct3D10.Buffer(Device, stream, bufferDescription);
}
Device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_graphDataVertexBuffer, sizeof(int) * 3, 0));
Device.InputAssembler.PrimitiveTopology = PrimitiveTopology.LineStrip;
Then constant buffer with parameters used in shader:
_controlInfoConstantBuffer = new ConstantBuffer<ControlParamsShaderData>(Device);
Device.VertexShader.SetConstantBuffer(0, _controlInfoConstantBuffer.Buffer);
To init animation Reset method was overriden like that:
base.Reset(args);
if (args.RenderSize.Width == 0) return;
_drawArgs = args;
InitVertexBuffer(dataLength);
_controlInfoConstantBuffer.Value = new ControlParamsShaderData
{
SamplesInControl = dataLength,
MinSignalDataY = -1500,
MaxSignalDataY = 1500
};
Device.VertexShader.SetConstantBuffer(0, _controlInfoConstantBuffer.Buffer);
The last step is RenderScene method:
public override void RenderScene(DrawEventArgs args)
{
if (args.RenderSize.Width == 0) return;
Device.ClearRenderTargetView(RenderTargetView, Color.Transparent);
using (var stream = _graphDataVertexBuffer.Map(MapMode.WriteDiscard, SharpDX.Direct3D10.MapFlags.None))
{
for (int i = 0; i < Data.Length; i++)
{
stream.Write(new Vector3(i, Data[i], 0));
}
}
_graphDataVertexBuffer.Unmap();
Device.Draw(Data.Length, 0);
}
Rendering is controlled by DispatcherTimer where OnTickMethod updates array with points coordinates and then invoke Render() method.
My question is simply, is that memory leak or something is created on each render iteration?
I don't change backbuffer or create another objects. Only change Data array, update it to GPU and Shaders process it to display.
My case is to display about 30 wpf controls width DirectX on one screen. Controls are with simple but realtime animation. Is that possible in that way?
Most likely you are leaking resources. You can see this by setting the static configuration property
SharpDX.Configuration.EnableObjectTracking = true;
then calling
SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects()
at various points in your application lifetime to see if anything is leaking (at least on the SharpDX side). You can edit your code to make sure to dispose these objects. Only enable object tracking while debugging - it hurts performance.
SharpDX used to release COM objects when the finalizer ran if the object had not already been Diposed (at least as in version 2.4.2), but later disabled that (they detail why in one of their changelogs, I forget which one).
Additionally, DirectX requires that you release objects in the reverse order they were created - this can create hard-to-debug memory leaks. So when your code is
var device = new Devie(...);
var effect = new Effec(Device, byteCode);
technique = effect.GetTechniqueByName(techniqueName);
inputLayout = new InputLayout(Device, _technique.GetPassByIndex(0).Description.Signature, ...);
then your dispose code has to be
_inputLayout.Dispose();
_technique.Dispose();
_effect.Dispose();
_device.Dispose();

Large method causing silverlight application to go into "Not responding" state

I am working on an application that plays videos through the silverlight MediaElement object.
I have a large method which is responsible for the following
Opens a FileInfo item on the local file path of the video and strips the file name to get the first portion of the filename which we use as part of the license acquisition process
Sets the LicenseAcquirer on the MediaElement
Sets the Source property of the MediaElement
When this method is called, it actually causes the application to go into a "Not reponding" state for a couple of seconds. How do I avoid this? I have tried putting this all into a background worker but I have to invoke the UI thread for almost all of the calls and this didnt help it seemed to actually make things slower.
I have a busy box that shows while this all happens but that actually stops reporting progress in those seconds where the application is not responding. I understand why this is happening - a lot of work happening on the main UI thread, but how do I avoid this?
This is the code that is causing the trouble:
private void SetupMediaElement(String mediaElementType)
{
Messenger.Default.Send("Loading video...", "SetNowWatchingVideoBusyBoxText");
Messenger.Default.Send(true, "SetNowWatchingVideoBusyBox");
try
{
if (_mainMediaElement != null)
{
VideoItem vi = CurrentSession.NowPlayingVideoItem;
if (vi != null)
{
CurrentVideoItem = vi;
MustShowImage = true;
if (vi.ID != string.Empty)
{
String mediaId = String.Empty;
if (vi.LocalFilePath != DEMOVIDEOPATH)
{
if (vi.LocalFilePath != String.Empty)
{
var fi =
new FileInfo(vi.LocalFilePath);
if (fi.Exists)
{
mediaId = fi.Name.Substring(fi.Name.LastIndexOf('-') + 1,
(fi.Name.LastIndexOf('.') -
(fi.Name.LastIndexOf('-') + 1)));
}
}
else
{
Debug.WriteLine("localFilePath is empty");
}
Debug.WriteLine("MediaId = " + mediaId +
", SessionId = " +
CurrentSession.LoggedOnUser.SessionId +
",Ticket = " +
CurrentSession.LoggedOnUser.Ticket);
string licenseURL = GetLicenseURL(mediaId, CurrentSession.LoggedOnUser.SessionId,
CurrentSession.LoggedOnUser.Ticket);
if (licenseURL != string.Empty)
{
var la = new LicenseAcquirer
{
LicenseServerUriOverride
=
new Uri(
licenseURL)
};
la.AcquireLicenseCompleted += la_AcquireLicenseCompleted;
_mainMediaElement.LicenseAcquirer = la;
}
var fileInfo = new FileInfo(vi.LocalFilePath);
string playURL = #"file://" +
Path.Combine(CoreConfig.HOME_FULL_PATH, fileInfo.Name);
playURL = playURL.Replace("\\", #"/");
VideoURL = playURL;
}
else
{
VideoURL = vi.LocalFilePath;
Messenger.Default.Send(false, "SetNowWatchingVideoBusyBox");
}
_totalDurationSet = false;
TotalTime = FormatTextHoursMinutesSecond(_mainMediaElement.NaturalDuration.TimeSpan);
SetSliderPosition();
}
}
else
{
Messenger.Default.Send(false, "SetNowWatchingVideoBusyBox");
}
}
else
{
Messenger.Default.Send(false, "SetNowWatchingVideoBusyBox");
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
VideoURL = DEMOVIDEOPATH;
Messenger.Default.Send(false, "SetNowWatchingVideoBusyBox");
}
}
Thanks
EDIT:
So it turns out that the method posted above is NOT the cause of the delay - that code executes in under a second. The problem comes in when the media element's source is set and it reads the file to the end - large files take time and this is the delay. Am opening a new question based on this.
You should do some diagnostics to determine which line(s) are truely costing all that time, its unlikely that amount of time is spread evenly across the whole function.
Place that line (or lines) in a background thread (hopefully that line doesn't need to be on the UI thread).
So it turns out that the method posted above is NOT the cause of the delay - that code executes in under a second. The problem comes in when the media element's source is set and it reads the file to the end - large files take time and this is the delay. Am opening a new question based on this.

NetConnect fails silently in Flash when called from SilverLight

This is a complex question, because there are a lot of moving parts. My apologies in advance.
I'm trying to write a Silverlight control that hosts a Flash camera and microphone (since Silverlight doesn't support these things natively, worse luck). I've written a short little Flex application ("WLocalWebCam.swf") which handles the camera, and exposes two external methods: connect(uri:String, streamName:String), and disconnect(). I can call these successfully through JavaScript as follows (simplified to remove error handling, etc.):
function connectWebCam(webCamID, rtmpUri, streamName) {
var flashCam = getWebCam(webCamID);
flashCam.Connect(rtmpUri, streamName);
}
function disconnectWebCam(webCamID) {
var flashCam = getWebCam(webCamID);
flashCam.Disconnect();
}
function getWebCam(id) {
return document.getElementById(id);
}
When I call these functions from another JavaScript source (e.g., a button click handler), the web cam connects correctly up to the RTMP server (I'm using Wowza). However, when I call exactly these same functions on the same page from Silverlight, the Flash camera fails to connect to the RTMP server.
/// <summary>
/// Connect() invokes the connectWebCam() JavaScript function contained in the WebCam.js file on the website.
/// The connectWebCam() method in turn calls the Connect() method on the contained Flash web cam object.
/// </summary>
public void Connect()
{
ScriptObject connectWebCam = (ScriptObject)HtmlPage.Window.GetProperty("connectWebCam");
connectWebCam.InvokeSelf(CameraID, RtmpUri.ToString(), CameraID);
}
However, it fails in an interesting fashion. The ActionScript connect() method gets called, it successfully calls getConnection(), but the handleNetStatus event handler method never gets called, and the Wowza server never sees an attempt to connect.
Here's the ActionScript code I'm using, this time with the debugging bits left in.
public function connect(uri:String, name:String):void
{
rtmpUri = uri;
streamName = name;
logMessage("Beginning attempt to open connection; rtmpUri=" + rtmpUri + "; streamName = " + streamName);
logMessage("Retrieving camera.");
cam = Camera.getCamera();
if( cam != null )
{
logMessage("Retrieved camera.");
cam.setMode( 320, 240, 20 );
cam.setQuality( 0,0 );
}
else
{
logMessage("Unable to retrieve camera instance.");
}
logMessage("Retrieving microphone.");
mic = new Microphone();
if (mic == null)
{
logMessage("Unable to retrieve microphone instance.");
}
logMessage("Retrieving NetConnection.");
chatNC = getConnection();
}
private function getConnection(): NetConnection
{
var nc: NetConnection = new NetConnection();
if (nc != null)
{
logMessage("Retrieved NetConnection().");
nc.client = this;
nc.objectEncoding = ObjectEncoding.AMF0;
nc.addEventListener( NetStatusEvent.NET_STATUS, this.handleNetStatus );
logMessage("Connecting to " + rtmpUri);
nc.connect(rtmpUri); // <-- We get successfully to this point.
}
else
{
logMessage("Unable to retrieve new NetConnection()");
}
return nc;
}
private function handleNetStatus( event:NetStatusEvent ):void
{
logMessage("[SYSTEM MESSAGE] net status " + event.info.code + " type " + event.type); // <-- We never get this far. This bit never gets called.
switch( event.info.code )
{
case "NetConnection.Connect.Success":
publishVideoStream();
break;
default:
Alert.show("Error connecting: " + event.info.code, "Error Connecting");
break;
}
}
This has got me seriously scratching my head.
Does anyone know why the exact same ActionScript would behave differently if called from Silverlight vs. being called from JavaScript? Any suggestions on troubleshooting it?
Sigh. Never mind. Turns out it makes a difference if you try to connect to http://localhost/videochat instead of rtmp://localhost/videochat. It all works as expected when you give it the right parameters. I must have looked at that code a hundred times before I spotted what I did wrong.

Resources