QR code scanning does not work in UWP - c#

I'm using ZXing.Net.Mobile and have the following code to scan the QR code.
await scanner.Scan().ContinueWith(t =>
{
if (t.Result != null)
HandleScanResult(t.Result);
});
scanner.UseCustomOverlay = false;
scanner.ScanContinuously(async (res) =>
{
var msg = "Found Barcode: " + res.Text;
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
ViewHelper.showMessage(msg, "");
});
});
I've tried both ContinueWith and ScanContinuosly but none of them work.
I get a camera view with red line but it does not scan the QR code.
Where am I going wrong.

I suppose you're using the ZXing.NET package?
Mike Taulty wrote a whole blog post series on an app with Scanning on Windows 8.1, then porting it to Windows 10 and even running it on HoloLens. The final post also has a small companion app that runs on UWP for simple scanning (with speech to command the app to scan).
In that sample, he's using following method:
ZXingQrCodeScanner.ScanFirstCameraForQrCode(
result =>
{
this.txtResult.Text = result?.Text ?? "none";
},
TimeSpan.FromSeconds(30));
There’s an assumption that the first camera found on the system should be used for QR code scanning but the classes that underpin this would allow for taking a more flexible approach and that ScanFirstCameraForQrCode function expands out into the following steps below
public static class ZXingQrCodeScanner
{
public static async void ScanFirstCameraForQrCode(
Action<Result> resultCallback,
TimeSpan timeout)
{
Result result = null;
var mediaFrameSourceFinder = new MediaFrameSourceFinder();
// We want a source of media frame groups which contains a color video
// preview (and we'll take the first one).
var populated = await mediaFrameSourceFinder.PopulateAsync(
MediaFrameSourceFinder.ColorVideoPreviewFilter,
MediaFrameSourceFinder.FirstOrDefault);
if (populated)
{
// We'll take the first video capture device.
var videoCaptureDevice =
await VideoCaptureDeviceFinder.FindFirstOrDefaultAsync();
if (videoCaptureDevice != null)
{
// Make a processor which will pull frames from the camera and run
// ZXing over them to look for QR codes.
var frameProcessor = new QrCaptureFrameProcessor(
mediaFrameSourceFinder,
videoCaptureDevice,
MediaEncodingSubtypes.Bgra8);
// Remember to ask for auto-focus on the video capture device.
frameProcessor.SetVideoDeviceControllerInitialiser(
vd => vd.Focus.TrySetAuto(true));
// Process frames for up to 30 seconds to see if we get any QR codes...
await frameProcessor.ProcessFramesAsync(timeout);
// See what result we got.
result = frameProcessor.QrZxingResult;
}
}
// Call back with whatever result we got.
resultCallback(result);
}
}
Source:
Mike Taulty's blog post
Sample app on GitHub
I hope this approach helps you forward.

You can try my ready solution:
Barcode_Scanner_UWP on GitHub
I'v tried to make adoption of VideoScanZXingWinRT repo
Both of them are using ZXing.Net
But in compare with old Mike Taulty sample could catch QR "on the fly"

Related

Listen for only an image in discord.net

I have an issue in which i'm looking for our discord bot to only look for images received and ignore any text typed.
From the guides I have read, I have yet to come across any that hasn't required a command.
I have tried to use a command with no command within the string, however it doesn't build as it doesn't contain a parameter.
Does anyone have any ideas how I can just listen for an image only?
Below is an example of my code.
private async Task _client_MessageReceived(SocketMessage arg)
{
var message = arg as SocketUserMessage;
var context = new SocketCommandContext(_client, message);
if (message.Author.IsBot) return;
int argPos = 0;
if (message.HasStringPrefix("!", ref argPos) || message.Attachments.Count > 0)
{
var result = await _commands.ExecuteAsync(context, argPos, _services);
if (!result.IsSuccess) Console.WriteLine(result.ErrorReason);
}
else
await message.DeleteAsync();
}
[Command("")]
public async Task Photo()
{
var attachments = Context.Message.Attachments;
WebClient myWebClient = new WebClient();
string file = attachments.ElementAt(0).Filename;
string url = attachments.ElementAt(0).Url;
myWebClient.DownloadFile(url, #"mydirect");
_ = Task.Run(async () =>
{
AWS.AWS.Get_kv_map(#"mydirect");
});
}
my sugestion is to check if message.Attachments != 0 ==> do your thing, with that you can check if it has any Attachments is on it and after that you can check if its ending on an .jpg or .png or so.
example:
if(message.Attachments.Count != 0){
var image attachements = message.Attachments.Where(x =>
x.Filename.EndsWith(".jpg") || x.Filename.EndsWith(".png") ||
x.Filename.EndsWith(".gif")); // or what you want as "image"
if(image.Any()){
// do your stuff from your method Photo() here or just call here your method your decision
}else{
// ignore or whatever you want to do it with it
}
I hope it helped and good luck on your project :D
var image = message.Attachments.Where(x => x.Filename.EndsWith("*.png") ...);
This code will be one of the great solution but If you want to check that's real image then.
First, download image.
Second check magic number.
https://en.wikipedia.org/wiki/List_of_file_signatures
This wikipedia link has list of magic number, for example, MZ means PE file.
If byte of file not starts with MZ, windows will deny of execution.

GetPreviewFrameASync Invalid parameter type

I am working in UWP and trying to make the following tutorial example work. In summary i am trying to get a frame from a MediaCapture and display it to an Image UWP Control element.
var previewProperties = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;
VideoFrame videoFrame = new VideoFrame(BitmapPixelFormat.Bgra8, (int)previewProperties.Width, (int)previewProperties.Height);
var source = new SoftwareBitmapSource();
var previewFrame = await _mediaCapture.GetPreviewFrameAsync(videoFrame);
SoftwareBitmap previewBitmap = videoFrame.SoftwareBitmap;
await source.SetBitmapAsync(previewBitmap);
img.Source = source;
When the GetPreviewFrameASync function is execute i get a runtime exception reffering Invalid parameter type. Have anyone experiencing the same problem before and what was the cause of it?
Thanks in advance
Turns out there was absolutely no problem with my code,but somehow the CAMERA was to blame for the error. Many others that ran my project had no issues and when I changed my camera everything was fine.If you are unlucky enough to experience the same problem try running it with another cam.
I have tested your segment code and reproduced your issue, the problem is you have not started previewing before GetPreviewFrameASync method executed. The following is the method of starting to preview.
private async Task StartPreviewAsync()
{
try
{
_mediaCapture = new MediaCapture();
await _mediaCapture.InitializeAsync();
_displayRequest.RequestActive();
DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;
}
catch (UnauthorizedAccessException)
{
}
try
{
PreviewControl.Source = _mediaCapture;
await _mediaCapture.StartPreviewAsync();
_isPreviewing = true;
}
catch (System.IO.FileLoadException)
{
}
}
For more please refer to Basic photo, video, and audio capture with MediaCapture. I have upload code sample to github. Please check!

Making conference calls (cellular not VoIP) in C# UWP

I'm trying to figure out how to make a conference call (adding and merging phone calls of different contacts - cellular not VoIP) using C# in UWP.
I see the sample code "PhoneCall" provded in github:
https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/PhoneCall
on how to dial a number:
public async void DialOnCurrentLineAsync(string PhoneNumber, string DisplayName)
{
if ((currentPhoneLine != null) && (PhoneNumber.Trim().Length > 0))
{
currentPhoneLine.Dial(PhoneNumber, DisplayName);
}
else
{
var dialog = new MessageDialog("No line found to place the call");
await dialog.ShowAsync();
}
}
But I don't see any part of the code to add and merge calls.
For now, there's no sucn built-in API for you to make conference call in UWP. It should be a feature request. You could submit your feature request on WP UserVoice.

MediaCapture VideoStabilization fails with 0xC00D4A3E

I'm working on a video recording app that supports the VideoStabilization effect, but when I start recording, I receive the following through the MediaCapture.Failed event almost instantly:
The sample allocator is currently empty, due to outstanding requests.
(0xC00D4A3E)
It only happens when I use the recommended configuration from the effect, though. If I don't call SetUpVideoStabilizationRecommendationAsync, it works fine.
Here is how I'm setting it up:
private MediaEncodingProfile _encodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
private async Task CreateVideoStabilizationEffectAsync()
{
var definition = new VideoStabilizationEffectDefinition();
_videoStabilizationEffect = (VideoStabilizationEffect)await _mediaCapture.AddVideoEffectAsync(definition, MediaStreamType.VideoRecord);
_videoStabilizationEffect.Enabled = true;
await SetUpVideoStabilizationRecommendationAsync();
}
private async Task SetUpVideoStabilizationRecommendationAsync()
{
var properties = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoRecord) as VideoEncodingProperties;
var recommendation = _videoStabilizationEffect.GetRecommendedStreamConfiguration(_mediaCapture.VideoDeviceController, properties);
if (recommendation.InputProperties != null)
{
await _mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoRecord, recommendation.InputProperties);
}
if (recommendation.OutputProperties != null)
{
_encodingProfile.Video = recommendation.OutputProperties;
}
}
private async Task StartRecordingAsync()
{
var videoFile = await KnownFolders.PicturesLibrary.CreateFileAsync("StableVideo.mp4", CreationCollisionOption.GenerateUniqueName);
await _mediaCapture.StartRecordToStorageFileAsync(_encodingProfile, videoFile);
}
The desiredProperties parameter of the GetRecommendedStreamConfiguration method needs to get MediaEncodingProfile that will be used when calling your choice of MediaCapture.StartRecordTo* (i.e. the "output properties") to see what your desired VideoEncodingProperties are.
The error is being triggered because the VideoEncodingProperties from the VideoDeviceController (i.e. the "input properties") are being passed instead. If you think about it, an instance of the the VideoDeviceController is already being passed in as a parameter to the method, so the effect can already access the information in that properties var; it wouldn't make much sense to have to pass those in separately at the same time. Instead, what it needs is information about the other endpoint. Does that make sense? At least that's how I try to rationalize it.
The official SDK sample for VideoStabilization on the Microsoft github repo shows how to do this correctly:
/// <summary>
/// Configures the pipeline to use the optimal resolutions for VS based on the settings currently in use
/// </summary>
/// <returns></returns>
private async Task SetUpVideoStabilizationRecommendationAsync()
{
Debug.WriteLine("Setting up VS recommendation...");
// Get the recommendation from the effect based on our current input and output configuration
var recommendation = _videoStabilizationEffect.GetRecommendedStreamConfiguration(_mediaCapture.VideoDeviceController, _encodingProfile.Video);
// Handle the recommendation for the input into the effect, which can contain a larger resolution than currently configured, so cropping is minimized
if (recommendation.InputProperties != null)
{
// Back up the current input properties from before VS was activated
_inputPropertiesBackup = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoRecord) as VideoEncodingProperties;
// Set the recommendation from the effect (a resolution higher than the current one to allow for cropping) on the input
await _mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.VideoRecord, recommendation.InputProperties);
Debug.WriteLine("VS recommendation for the MediaStreamProperties (input) has been applied");
}
// Handle the recommendations for the output from the effect
if (recommendation.OutputProperties != null)
{
// Back up the current output properties from before VS was activated
_outputPropertiesBackup = _encodingProfile.Video;
// Apply the recommended encoding profile for the output, which will result in a video with the same dimensions as configured
// before VideoStabilization was added if an appropriate padded capture resolution was available. Otherwise, it will be slightly
// smaller (due to cropping). This prevents upscaling back to the original size, which can result in a loss of quality
_encodingProfile.Video = recommendation.OutputProperties;
Debug.WriteLine("VS recommendation for the MediaEncodingProfile (output) has been applied");
}
}

Amazon AWS Simple Workflow Service SWF C# Sample

I was wondering if there are any SWF workflow C# sample code available for the AWS .NET SDK?
AWS Forum Post: https://forums.aws.amazon.com/thread.jspa?threadID=122216&tstart=0
As part of getting familiar with SWF, I ended up writing a common case library that I hope others can use as well. It's called SimpleWorkflowFramework.NET and is available as open source at https://github.com/sdebnath/SimpleWorkflowFramework.NET. It definitely could use a lot of help, so if you are interested, jump right in! :)
I have developed an open source .NET library- Guflow to program Amazon SWF. Here is how you can write a workflow to transcode the video:
[WorkflowDescription("1.0")]
public class TranscodeWorkflow : Workflow
{
public TranscodeWorkflow()
{
//DownloadActivity is the startup activity and will be scheduled when workflow is started.
ScheduleActivity<DownloadActivity>().OnFailure(Reschedule);
//After DownloadActivity is completed TranscodeActivity activity will be scheduled.
ScheduleActivity<TranscodeActivity>().AfterActivity<DownloadActivity>()
.WithInput(a => new {InputFile = ParentResult(a).DownloadedFile, Format = "MP4"})
ScheduleActivity<UploadToS3Activity>().AfterActivity<TranscodeActivity>()
.WithInput(a => new {InputFile = ParentResult(a).TranscodedFile});
ScheduleActivity<SendConfirmationActivity>().AfterActivity<UploadToS3Activity>();
}
private static dynamic ParentResult(IActivityItem a) => a.ParentActivity().Result();
}
In above example I have left out task routing for clarity.
Here is how you can create an activity:
[ActivityDescription("1.0")]
public class DownloadActivity : Activity
{
//It supports both sync/async method.
[ActivityMethod]
public async Task<Response> Execute(string input)
{
//simulate downloading of file
await Task.Delay(10);
return new Response() { DownloadedFile = "downloaded path", PollingQueue = PollingQueue.Download};
}
public class Response
{
public string DownloadedFile;
}
}
For clarity I'm leaving out examples of other activities. Guflow it supported by documentation, tutorial and samples.

Categories