I want to return a photo using PhotoChooserTask like this:
private void getimage_Click(object sender, EventArgs e)
{
photoChooserTask = new PhotoChooserTask();
photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
try
{
photoChooserTask.Show();
}
catch (System.InvalidOperationException ex)
{
MessageBox.Show("An error occurred.");
}
}
void photoChooserTask_Completed(object sender, PhotoResult ee)
{
if (ee.TaskResult == TaskResult.OK)
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(ee.ChosenPhoto);
if (ee.TaskResult == TaskResult.OK && ee.Error == null)
{
WriteableBitmap wb = new WriteableBitmap(bmp);
notes.Add(new chatinfo() { sendimage = bmp });
noteListBox.ItemsSource = null;
noteListBox.ItemsSource = notes;
}
}
}
but everytime the program arrived here:"bmp.SetSource(ee.ChosenPhoto);" A SocketException will be called.
private void OnRecieveFrom()
{
var receiveArgs = new SocketAsyncEventArgs();
receiveArgs.RemoteEndPoint = this.IPEndPoint;
receiveArgs.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
var strBdr = new StringBuilder();
receiveArgs.Completed += (__, result) =>
{
string message = CreateMessage(result);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
this.RaiseReceived(message);
});
socket.ReceiveFromAsync(receiveArgs);
};
socket.ReceiveFromAsync(receiveArgs);
}
The SocketException is called by " socket.ReceiveFromAsync(receiveArgs);"
I just want to get a photo from the phone,and there is not send or recieve operation.I don't know why receive function was called.
Would the app lose the socket communication when it jumps to the photo album (the value "RemoteEndPoint" of socket change to null)? p.s. "socket" is an object of class "Socket".
If so, should I recreate the "socket" every time the app jumps out?
Thank you!
Once the PhotoChooserTask is called your app will be Fast App Switched (or maybe even Tombstoned).
Either way your socket will be closed. You'll have to reopen your socket when your app is Activated again.
Related
I keep getting a "Parameter is not valid" error or a memory leak (and the picture doesn't update) when I run my code. I am trying to get frames from a local IP camera using AForge.Net. The exact error code that I get is:
"An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll
Parameter is not valid."
In my code, feed is the name of the winforms picture box.
private void Form1_Load(object sender, EventArgs e) {
Console.WriteLine(camaddress);
stream.Source = camaddress;
stream.Login = camUser;
stream.Password = camPass;
stream.Start();
//PictureBox.CheckForIllegalCrossThreadCalls = false;
CaptureCamera();
isCameraRunning = true;
}
private void CaptureCamera() {
try {
camera = new Thread(new ThreadStart(CaptureCameraCallback));
camera.Start();
} catch (Exception e) {
Debug.Write("Exception encountered trying to capture camera:\n" + e.ToString() + "\n");
}
}
private void CaptureCameraCallback() {
log.Information("Camera Opened", testID);
guiLogWrite("Camera Opened");
while (stream.IsRunning) {
stream.NewFrame += new NewFrameEventHandler(VideoStream_NewFrame);
}
}
private void VideoStream_NewFrame(object sender, NewFrameEventArgs eventArgs) {
try {
//Image FrameData = new Bitmap(eventArgs.Frame);
if (feed.Image != null) feed.Image.Dispose();
Bitmap FrameData = AForge.Imaging.Image.Clone(eventArgs.Frame);
SetPicture(FrameData);
FrameData.Dispose();
} catch { }
}
private void SetPicture(Image img) {
if (this.InvokeRequired) {
this.Invoke(new MethodInvoker(delegate { SetPicture(img); }));
} else {
this.feed.Image = img;
}
This is my first time posting on Stack Overflow so please let me know if I have forgotten something. I've spent hours looking at other stackoverflow threads and Google trying to find a solution.
I have a Xamarin.Forms application that supports only UWP. I cannot find a way to print a pdf document. Whatever I have seen on the web, for some reason doesn't work for me. E.g. I tried
https://www.syncfusion.com/kb/8767/how-to-print-pdf-documents-in-xamarin-forms-platform
It lets me print, but the preview in the print dialog never shows up, and the progress indicator just keeps rotating forever.
I also tried http://zawayasoft.com/2018/03/13/uwp-print-pdf-files-silently-without-print-dialog/
This gives me errors that I cannot fix.
So I wonder if somebody can suggest something else that would actually work. Maybe something newer than what I have tried (I use VS 2017). Printing without the printing dialog would be preferable.
Thank you in advance.
I used a very dirty hack to do that!
What I had to do was to try to print the image version of the pdf (I did the conversion in backend) and then used the following DependencyInjection:
Inside my Print class in UWP project:
class Print : IPrint
{
void IPrint.Print(byte[] content)
{
Print_UWP printing = new Print_UWP();
printing.PrintUWpAsync(content);
}
}
and the class responsible for printing in uwp:
public class Print_UWP
{
PrintManager printmgr = PrintManager.GetForCurrentView();
PrintDocument PrintDoc = null;
PrintDocument printDoc;
PrintTask Task = null;
Windows.UI.Xaml.Controls.Image ViewToPrint = new Windows.UI.Xaml.Controls.Image();
public Print_UWP()
{
printmgr.PrintTaskRequested += Printmgr_PrintTaskRequested;
}
public async void PrintUWpAsync(byte[] imageData)
{
int i = 0;
while (i < 5)
{
try
{
BitmapImage biSource = new BitmapImage();
using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
await stream.WriteAsync(imageData.AsBuffer());
stream.Seek(0);
await biSource.SetSourceAsync(stream);
}
ViewToPrint.Source = biSource;
if (PrintDoc != null)
{
printDoc.GetPreviewPage -= PrintDoc_GetPreviewPage;
printDoc.Paginate -= PrintDoc_Paginate;
printDoc.AddPages -= PrintDoc_AddPages;
}
this.printDoc = new PrintDocument();
try
{
printDoc.GetPreviewPage += PrintDoc_GetPreviewPage;
printDoc.Paginate += PrintDoc_Paginate;
printDoc.AddPages += PrintDoc_AddPages;
bool showprint = await PrintManager.ShowPrintUIAsync();
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
}
// printmgr = null;
// printDoc = null;
// Task = null;
PrintDoc = null;
GC.Collect();
printmgr.PrintTaskRequested -= Printmgr_PrintTaskRequested;
break;
}
catch (Exception e)
{
i++;
}
}
}
private void Printmgr_PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
{
var deff = args.Request.GetDeferral();
Task = args.Request.CreatePrintTask("Invoice", OnPrintTaskSourceRequested);
deff.Complete();
}
async void OnPrintTaskSourceRequested(PrintTaskSourceRequestedArgs args)
{
var def = args.GetDeferral();
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
args.SetSource(printDoc.DocumentSource);
});
def.Complete();
}
private void PrintDoc_AddPages(object sender, AddPagesEventArgs e)
{
printDoc.AddPage(ViewToPrint);
printDoc.AddPagesComplete();
}
private void PrintDoc_Paginate(object sender, PaginateEventArgs e)
{
PrintTaskOptions opt = Task.Options;
printDoc.SetPreviewPageCount(1, PreviewPageCountType.Final);
}
private void PrintDoc_GetPreviewPage(object sender, GetPreviewPageEventArgs e)
{
printDoc.SetPreviewPage(e.PageNumber, ViewToPrint);
}
}
Please note that this is not a perfect solution and sometimes it crashes without actually being able to trace the exception (which is really strange) so I am sure there must be better answers even though it does the job.
currently my program can open the webcam then dynamic capture the human face, however, I have no idea how to stop the camera because it will keep capturing the face even the windows are closed.
private static VideoCapture _cameraCapture;
public VideoSurveilance()
{
InitializeComponent();
Run();
}
void Run()
{
try
{
_cameraCapture = new VideoCapture();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
return;
}
_fgDetector = new
Emgu.CV.VideoSurveillance.BackgroundSubtractorMOG2();
_blobDetector = new CvBlobDetector();
_tracker = new CvTracks();
Application.Idle += ProcessFrame;
}
private void btnStopCamera_Click(object sender, EventArgs e)
{
_cameraCapture.Pause();//not working
_cameraCapture.Stop();//not working
_cameraCapture.Dispose();//worked but crashed due to memory issue
this.Close();
faceManipulate fm = new faceManipulate();
fm.Show();
Memory issue already solved. However, Dispose will cause the process frame Null Reference Object.
void ProcessFrame(object sender, EventArgs e)
{
Mat frame = _cameraCapture.QueryFrame();
Mat smoothedFrame = new Mat();
CvInvoke.GaussianBlur(frame, smoothedFrame, new Size(3, 3), 1);
}
You already solved the issue, you should call the Dispose method.
CameraCapture implements DisposableObject, you should not have it as a static variable, instead you should keep it as a variable and dispose when you are done with it.
I saw that you said that it "worked but crashed due to memory issue", if this is still a problem post a question or comment below describing the memory issue.
I noticed this code challenge is old and not many solutions have been posted at this time. However, the provided response will not really solve the issue. I encountered the same problem and found a way around it to avoid the memory NullReferenceError. I will use my own code here for convenience, but the challenges are the same, so it applies. Pick the code section that applies to your instance.
MY OBSERVATIONS
Any Bitmap object has to be disposed (bitmap.Dispose())
properly to free the memory from overload. The natural garbage
collector seems not to pick it up at the end of its function.
The Emgu.CV.Capture _capture; object has to be disposed
(_capture.Dsipose()) as well but has to be done with boolean control to avoid a NullReference error.
public partial class Main : Form
{
bool isStreaming;
bool onCamera;
Capture _capture;
public Main()
{
InitializeComponent();
}
private void btnReset_Click(object sender, EventArgs e)
{
onCamera = false;
isStreaming = false;
if (_capture != null) _capture.Dispose();
if (picStream.Image != null) picStream.Image = null;
if (picCapture.Image != null) picCapture.Image = null;
}
private void btnStream_Click(object sender, EventArgs e)
{
try
{
onCamera = true;
if (_capture != null) _capture.Dispose();
_capture = new Capture();
labelStatus.Text = "Streaming...";
isStreaming = true;
StreamVideo();
Application.Idle += Streaming;
}
catch {}
}
private void Streaming(object sender, EventArgs e)
{
try
{
if(onCamera && isStreaming)
{
if (picStream.Image != null) picStream.Image = null;
var img = _capture.QueryFrame().ToImage<Bgr, byte>();
var bmp = img.Bitmap;
picStream.Image = bmp;
}
}
catch {}
}
private void btnCapture_Click(object sender, EventArgs e)
{
onCamera = true;
CaptureImage();
labelStatus.Text = "Captured!";
if (picCapture.Image != null) picCapture.Image = null;
picCapture.Image = picStream.Image;
}
private void btnLoadCamera_Click(object sender, EventArgs e)
{
try
{
if (!isStreaming)
{
_capture = new Capture();
StreamVideo();
pnlStatus.BackColor = Color.DimGray;
}
else
{
_capture.Dispose();
Application.Idle -= Streaming;
picStream.Visible = true;
picStream.Image = null;
picCapture.Visible = false;
picCapture.Image = null;
isStreaming = false;
pnlStatus.BackColor = Color.DimGray;
}
}
catch {}
}
}
1: Can someone explain the last line of the first function to me?
2: The second function doesn't work. Please tell me why.The PHP script is fetching the data.
I edited the code to get this, but the app now crashes with a System nullreferenceexception.
Please help.
private void checkbutton_Click(object sender, RoutedEventArgs e)
{
statustext.Text = "Checking for new score";
var webclient = new WebClient();
webclient.OpenReadCompleted += new OpenReadCompletedEventHandler(getscores_OpenReadCompleted);
webclient.OpenReadAsync(new Uri("http://example.com/get.php?"+DateTime.Now));
}
void getscores_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
StreamReader s = null;
Stream reply=null;
try
{
reply = (Stream)e.Result;
s = new StreamReader(reply);
}
catch
{
statustext.Text = "ERROR IN FETCHING";
}
scorebox.Text = s.ReadToEnd();
statustext.Text = "DoNE";
}
The last line of the first method is attaching a handler to an event. It is saying that when the OpenReadCompleted event fires, that is to say when the read completes, the getscores_OpenReadCompleted method should be called.
The getscores_OpenReadCompleted doesn't work because it's trying to access a UI element from a non-UI thread.
You're also adding the handler after starting the asynchronous operation, so while it's unlikely, it's certainly possible that the operation completes very quickly and the event is fired before you add the handler. While this situation would be very unusual, it's fixed very quickly and easily by simply adding the handler before you start the asynchronous operation.
There are a couple of issues here:
Register the delegate before the call to OpenReadAsync
Read the stream from the event arguments and close the stream when you're done.
private void checkbutton_Click(object sender, RoutedEventArgs e)
{
statustext.Text = "Checking for new score";
var webclient = new WebClient();
webclient.OpenReadCompleted += new OpenReadCompletedEventHandler(getscores_OpenReadCompleted);
webclient.OpenReadAsync(new Uri("http://example.com/get.php?"+DateTime.Now));
}
void getscores_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
Stream reply = null;
StreamReader s = null;
string outputText = string.Empty;
try
{
reply = (Stream)e.Result;
s = new StreamReader(reply);
outputText = s.ReadToEnd();
}
finally
{
if (s != null)
{
s.Close();
}
if (reply != null)
{
reply.Close();
}
}
statustext.Text = outputText;
}
See the usage of the OpenReadAsync method here:
http://msdn.microsoft.com/en-us/library/system.net.openreadcompletedeventhandler(v=vs.110).aspx
and here
http://msdn.microsoft.com/en-us/library/ms144211(v=vs.110).aspx
I've got this code and I'm using it to show a button which allows the user to choose an image from his library and use it as a background for my app.
So I create a PhotoChooserTask, set it to show the camera and bind it to a method that has to be executed when the task is completed.
The button will start the task by showing the PhotoChooserTask.
The action to do on complete is quite easy, I've just got to set a boolean value and update an image source.
PhotoChooserTask pct_edit = new PhotoChooserTask();
pct_edit.ShowCamera = true;
pct_edit.Completed += pct_edit_Completed;
Button changeImageButton = new Button { Content = "Change Image" };
changeImageButton.Tap += (s, e) =>
{
pct_edit.Show();
};
void pct_edit_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
bi.SetSource(e.ChosenPhoto);
IsRebuildNeeded = true;
}
}
The problem is that it won't show the PhotoChooserTask but it will give me an exception, taking me to
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
Debugger.Break();
}
}
in App.xaml.cs.
This looks weird as I've got another PhotoChooserTask in the same class and this one works fine.
What's wrong with it?
VisualStudio won't even tell me what's the exception and so there's no way to figure it out!
EDIT:
I just found out that the exception is thrown when I call
pct_edit.Show();
in the button's tap event.
You should be defining your chooser as a field in your class. It's a requirement that you have page scope for the PhotoChooser. You then subscribe to it in your constructor. This is stated on the MSDN here
class SomeClass
{
readonly PhotoChooserTask pct_edit = new PhotoChooserTask();
SomeClass()
{
pct_edit.ShowCamera = true;
pct_edit .Completed += new EventHandler<PhotoResult>(pct_edit_Completed);
}
}
You can use try to check what is the problem
changeImageButton.Tap += (s, e) =>
{
try
{
PhotoChooserTask pct_edit = new PhotoChooserTask();
pct_edit.ShowCamera = true;
pct_edit.Completed += (s,e) =>
{
if (e.TaskResult == TaskResult.OK)
{
var bi = new BitmapImage() // maybe you didn't initialize bi?
bi.SetSource(e.ChosenPhoto);
IsRebuildNeeded = true;
}
}
pct_edit.Show();
}
catch (Exception ex)
{
Message.Show(ex.Message);
}
};
Put brakepoint on Message, then you can check everything inside ex.