I have a program in c# which uses my local webcam, to capture and store images. I have buttons to click on start,stop,continue n etc.When I run the program it works properly for the first time after I turn my system on, but in the consecutive executions of the same thing I get an error (in pop-up window):
An error occurred while capturing the video image. The video capture will now be terminated. Object reference not set to an instance of the object.
for which I assume that it might be because of the camera device, not releasing the memory it used. So how do I programatically free it up, when I click on the exit button? Below is part of the program and i get error in the webcam.start(0) method
namespace WinFormCharpWebCam
{
class WebCam
{
private WebCamCapture webcam;
private System.Windows.Forms.PictureBox _FrameImage;
private int FrameNumber = 30;
public void InitializeWebCam(ref System.Windows.Forms.PictureBox ImageControl)
{
webcam = new WebCamCapture();
webcam.FrameNumber = ((ulong)(0ul));
webcam.TimeToCapture_milliseconds = FrameNumber;
webcam.ImageCaptured += new WebCamCapture.WebCamEventHandler(webcam_ImageCaptured);
_FrameImage = ImageControl;
}
void webcam_ImageCaptured(object source, WebcamEventArgs e)
{
_FrameImage.Image = e.WebCamImage;
}
public void Start()
{
webcam.TimeToCapture_milliseconds = FrameNumber;
webcam.Start(0); //error pops up when the execution comes to this method
}
public void Stop()
{
webcam.Stop();
}
public void Continue()
{
// change the capture time frame
webcam.TimeToCapture_milliseconds = FrameNumber;
// resume the video capture from the stop
webcam.Start(this.webcam.FrameNumber);
}
public void ResolutionSetting()
{
webcam.Config();
}
public void AdvanceSetting()
{
webcam.Config2();
}
}
}
You have a NullReferenceException thrown, not OutOfMemoryException.
Check your call stack to pinpoint where it originates. You can debug your app with debugger set to break on exception thrown, so it will break right where your exception occurs (press CRTL+D, E to open exceptions window in VS.NET).
From the error you are getting, I am guessing you downloaded the EasyWebCam Library.
If that is correct then here's how I worked around it:
1. I installed the Cyberlink's Youcam software on my machine.
2. Whenever I start my own application, the EasyWebCam library detects the Youcam WebSplitter on machine and prompts me to select either that or the default webcam driver.
3. I select the YouCam WebSplitter and the app works fine with it.
At this point, there comes along another snag: the Youcam process doesn't terminate when my application closes.
How I fixed it?
I had to get the Youcam process and Kill() it when my application window's about to exit.
This ugly solution worked.
Related
I'm making a game on Unity 5.5 and I've followed Google's Official AdMob Getting Started Guide to integrate AdMob into my game (currently iOS-only, but Android will also follow when I get this working).
I've set up my game at the AdMob console and created a reward-based video ad.
I've added the GoogleMobileAds.framework into my built project in Xcode.
I've made sure I'm linking against the newly-added framework too.
Downloaded the Unity package and integrated it into my project as required.
I've hooked up to event handlers: My ad gets loaded with no problem, no failure.
When I try to display the ad on iOS, ad.IsLoaded(); returns false even though it has just loaded (my OnAdLoaded event of the ad is firing). In Unity editor, I'm seeing the expected dummy methods being called at correct order (though nothing is being displayed, which I think is the expected behavior on Unity's own editor).
Here is my code for loading ads (of course, my publisher and ad unit IDs are redacted):
public class AdManager : MonoBehaviour {
static RewardBasedVideoAd ad;
static UIManager uiManager;
#if UNITY_ANDROID
static string adUnitId = "ca-app-pub-XXX/YYY";
#elif UNITY_IPHONE
static string adUnitId = "ca-app-pub-XXX/YYY";
#else
static string adUnitId = "unexpected_platform";
#endif
static int headstartPoints;
// Use this for initialization
void Start () {
uiManager = GameObject.Find("Scripts").GetComponent<UIManager>();
ad = RewardBasedVideoAd.Instance;
ad.OnAdRewarded += Ad_OnAdRewarded;
ad.OnAdClosed += Ad_OnAdClosed;
ad.OnAdFailedToLoad += Ad_OnAdFailedToLoad;
ad.OnAdLoaded += Ad_OnAdLoaded;
headstartPoints = 0;
RequestNewAd();
}
void Ad_OnAdFailedToLoad (object sender, AdFailedToLoadEventArgs e)
{
Debug.Log("Ad failed to load.");
}
void Ad_OnAdLoaded (object sender, System.EventArgs e)
{
Debug.Log("Ad loaded.");
}
void Ad_OnAdClosed (object sender, System.EventArgs e)
{
Debug.Log("Ad was closed, proceeding to game without rewards...");
}
void Ad_OnAdRewarded (object sender, Reward e)
{
Debug.Log("Ad rewarded.");
headstartPoints = (int)e.Amount;
}
public static int GetAndConsumeRewards(){
int points = headstartPoints;
headstartPoints = 0;
return points;
}
public static void RequestNewAd(){
Debug.Log("Requested new ad.");
AdRequest request = new AdRequest.Builder().Build();
ad.LoadAd(request, adUnitId);
}
public static void DisplayAdOrProceed(){
if(ad.IsLoaded()){
ad.Show();
Debug.Log("Ad was loaded, displaying ad...");
}else{
Debug.Log("Ad wasn't loaded, skipping ad...");
uiManager.ProceedToGame();
}
}
// Update is called once per frame
void Update () {
}
}
I've never seen OnAdFailedToLoad method being called, and I always see OnAdLoaded being called, so there doesn't seem to be a problem there. But when I check ad.IsLoaded() after ad is loaded, for some weird reason it's false. Please note that RewardBasedVideoAd is a singleton object as stated in Google's docs.
What am I doing wrong?
UPDATE: I am calling RequestNewAd() as soon as the app starts and also on each "level" start (think of it like one level is roughly ~30 seconds) and DisplayAdOrProceed() on death (e.g. end of the level). When DisplayAdOrProceed() is called, the ad's loaded method is always called (unless I have a connection problem but that's not the case here).
UPDATE 2: Just noticed that there is a really suspicious stack trace on "ad load" event:
Ad loaded.
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
UnityEngine.Debug:Log(Object)
AdManager:Ad_OnAdLoaded(Object, EventArgs)
System.EventHandler`1:Invoke(Object, TEventArgs)
GoogleMobileAds.Api.RewardBasedVideoAd:<RewardBasedVideoAd>m__8(Object, AdFailedToLoadEventArgs)
System.EventHandler`1:Invoke(Object, TEventArgs)
GoogleMobileAds.iOS.RewardBasedVideoAdClient:RewardBasedVideoAdDidFailToReceiveAdWithErrorCallback(IntPtr, String)
I can see that the ad load event is fired from a method named for a failure handler (RewardBasedVideoAdDidFailToReceiveAdWithErrorCallback, GoogleMobileAds.Api.RewardBasedVideoAd:<RewardBasedVideoAd>m__8(Object, AdFailedToLoadEventArgs)). However, it's calling the ad load event and not any failure handler. I have no idea what's going on or if it's a poorly-designed naming convention or not.
Okay after diving literally into the IL2CPP-generated C++ code in the Xcode project, I've realized that the SDK is calling the incorrect method. The ad is failing to load with error "No ad to show", but incorrectly firing up the ad load method. I'll make additional changes to my code to detect if it's being loaded correctly.
Terrible bug (or design decision), Google. I hope this gets fixed soon.
I am trying to Network a small 2 player Unity game. This is my first go at networking, so please feel free to correct me on anything I am doing wrong. I am attempting to make a simple matchmaking service where, on the main menu of the game, a player can click the Find Match button. This will execute the following function
private HostData[] hostList;
private const string typeName = "UniqueGameName";
private const string gameName = "RoomName";
public void FindMatch() {
RefreshHostList();
if (hostList != null) {
JoinServer(hostList[0]);
} else {
StartServer();
}
}
And here are the corresponding methods called in that function.
private void RefreshHostList()
{
MasterServer.RequestHostList(typeName);
}
void OnMasterServerEvent(MasterServerEvent msEvent)
{
if (msEvent == MasterServerEvent.HostListReceived)
hostList = MasterServer.PollHostList();
}
private void JoinServer(HostData hostData)
{
Network.Connect(hostData);
}
private void StartServer()
{
Network.InitializeServer(2, 25000, !Network.HavePublicAddress());
MasterServer.RegisterHost(typeName, gameName);
}
The idea is, when the player clicks Find Match, it will refresh the host list. If it finds a host, it will join their server and begin a match. If it doesn't, it will begin its own server and wait for another player. When testing this, the first player that clicks Find Match is able to start a server, but then the second player receives the error message "...Is the listen port already in use?". When I debug and step through my program, the second player's hostList is always null, even with the first players successful server creation and registration.
Are you using both instances of app on same machine? If you occupy network port once then you are not able to initialize server on same port on the same machine.
In general I would recommend looking into SingalR technology for your needs, it uses websockets.
I've tried following several tutorials an have seem to be having trouble.
I've got an existing program that i'm trying to add a directx window to as an additional popup forum that will run as a child to the main application form.
Here is the windows form class:
public partial class DxWindow : Form
{
Device device;
public DxWindow()
{
InitializeComponent();
initDevice();
}
private void initDevice()
{
MessageBox.Show("hello");
PresentParameters pp = new PresentParameters();
pp.Windowed = true;
pp.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Hardware, this, CreateFlags.HardwareVertexProcessing, pp);
}
private void Render()
{
//render stuff
}
private void DxWindow_Paint(object sender, PaintEventArgs e)
{
Render();
}
}
and here is where i initialize the form (from a UI button in main window)
private void toolStripButton3_Click_1(object sender, EventArgs e)
{
if (DirectxWindow == null)
{
DirectxWindow = new DxWindow();
DirectxWindow.Show();
}
}
When i run the program and click the button. it seems create the form in memory but never shows up. when i step through it in the debugger, it gets to "DirectxWindow = new DxWindow();" and then automatically jumps out of break mode and continues running with the main window frozen and no new Dxwindow().
when i break execution is seems to still be on "DirectxWindow = new DxWindow();"
Also, "MessageBox.Show("hello");" in the DxWindow constructor is never called"
Edit: I've deduced that as soon as it hits "PresentParameters pp = new Microsoft.DirectX.Direct3D.PresentParameters();" the application becomes unresponsive without throwing any errors.
Turns out my problem was needing to use
<startup useLegacyV2RuntimeActivationPolicy="true">
in the "App.config" File
Solution was found here: Mixed mode assembly is built against version 'v1.1.4322'
Although i never got the error as described by the OP. i simply had this problem as described in the comments:
"Thank you!!!! This is the weirdest problem I'd ever encountered. In VS 2012 .Net 4.0 my application would just hang the moment I initialized any variable of a type related to this DLL. I'd never seen anything like it. Couldn't find anything about the problem until I found this!" – Quinxy von Besiex
I made a program that handles NFC tags back in 2013, today after two years of pause on that program i continued with it, and ran into some strange problem. In the program i read NFC tags which are writen with a "window.Someid" so they are app specific.
For some reason, the program works perfectly when scanning the NFC tag, except, when i want to scan the tag for the second time, the handler doesn't fire. any idea what causes this? (i see no error message).
Here's my code:
ProximityDevice PDevice;
private long SubscriptionID = -1;
// Constructor
public MainPage()
{
InitializeComponent();
PDevice = ProximityDevice.GetDefault();
// subscribe for messages
SubscriptionID = PDevice.SubscribeForMessage("Windows.SomeMsg", ProximityMessageRcvd);
}
private void ProximityMessageRcvd(ProximityDevice sender, ProximityMessage message)
{
Debug.WriteLine("Message");
}
I'm having the same problem posed here:
http://social.msdn.microsoft.com/Forums/wpapps/en-us/af8615e7-8e90-4069-aa4d-3c4a84a6a3d0/windows-phone-8-fast-app-resume-with-deeplinks?forum=wpdevelop
I'm no C# or WP expert, so please bear with me.
I have secondary tiles which link to "/MainPage.xaml?id=XX".
I have fast app resume enabled. (ActivationPolicy="Resume" in the app manifest)
I only have one page in my app: MainPage.xaml.
Problem: When I resume the app using a secondary tile ("/MainPage.xaml?id=XX"), I get a brief view of the previous instance (that would have resumed) and then the MainPage initializes again, creating a new instance. In effect, the app is loading from scratch after giving me a peek of what was previously open.
That is obviously undesired behavior. I want to use the existing instance to perform my task.
Attempt 1:
Use e.Cancel = true; to cancel the navigation to the MainPage.xaml:
(using the App.xaml.cs code from the official Fast App Resume sample to identify how the app was launched)
...
else if (e.NavigationMode == NavigationMode.New && wasRelaunched)
{
// This block will run if the previous navigation was a relaunch
wasRelaunched = false;
if (e.Uri.ToString().Contains("="))
{
// This block will run if the launch Uri contains "=" (ex: "id=XX") which
// was specified when the secondary tile was created in MainPage.xaml.cs
sessionType = SessionType.DeepLink;
e.Cancel = true; // <======================== Here
// The app was relaunched via a Deep Link.
// The page stack will be cleared.
}
}
...
Problem: In doing so, my OnNavigatedTo event handlers never fire, so my query string is never parsed.
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
String navId;
if (e.NavigationMode != System.Windows.Navigation.NavigationMode.Back)
{
if (NavigationContext.QueryString.TryGetValue("id", out navId))
{
MessageBox.Show(navId.ToString()); // Not reached
}
}
...
Attempt 2:
Use e.Cancel = true; to cancel the navigation to the MainPage.xaml, AND pass the Uri to a method in MainPage:
// App.xaml.cs
...
else if (e.NavigationMode == NavigationMode.New && wasRelaunched)
{
// This block will run if the previous navigation was a relaunch
wasRelaunched = false;
if (e.Uri.ToString().Contains("="))
{
// This block will run if the launch Uri contains "=" (ex: "id=XX") which
// was specified when the secondary tile was created in MainPage.xaml.cs
sessionType = SessionType.DeepLink;
e.Cancel = true;
MainPage.GoToDeepLink(e.Uri); // <======================== Here
// The app was relaunched via a Deep Link.
// The page stack will be cleared.
}
}
...
// MainPage.xaml.cs
public static void GoToDeepLink(Uri uri) // <======================== Here
{
// Convert the uri into a list and navigate to it.
string path = uri.ToString();
string id = path.Substring(path.LastIndexOf('=') + 1);
MyList list = App.ViewModel.ListFromId(Convert.ToInt32(id));
pivotLists.SelectedItem = list;
}
Problem: I get an error that pivotLists is non-static and thus requires an object reference. I think that in order to get this to work I'd need to create a new instance of MainPage (MainPage newMainPage = new MainPage();) and call newMainPage.pivotLists.SelectedItem = list; -- BUT I don't know how to use newMainPage instead of the existing one/replace it... or if that's something I want/won't cause further problems/complications.
I don't know what the solution is to this problem, and I may be going in the completely wrong direction. Please keep all suggestions in simple terms with code examples if you can, I'm still learning.
Thanks for any help.
It seems that when you reopen your App from secondary tile, then it's reactivated and new instance of MainPage is created (even if there is one from previous run). If I understood you correctly, I've managed to do such a thing:
In app.xaml.cs:
I've added a variable which indicates if I should return to previous MainPage after Navigating from secondary tile - it needs to be static as I want to have access to it from MainPage
public static bool returnPage = false;
In RootFrame_Navigating I'm setting this variable to true in:
// ...
else if (e.NavigationMode == NavigationMode.New && wasRelaunched)
{
// This block will run if the previous navigation was a relaunch
wasRelaunched = false;
returnPage = true;
// ...
In ClearBackStackAfterReset - prevent from deleting the old Page, when returning:
// ...
if (e.NavigationMode != NavigationMode.New || returnPage)
return;
// ...
In MainPage.cs:
I've changed a little constructor, as I don't want to see a blink of a new Page:
public MainPage()
{
if (!App.returnPage)
InitializeComponent();
}
In MainPage I've also variable which is passed from secondary tile - it's also static, as I need only one instance of it:
private static string navId = "";
And the core of the trick - OnNavigatedTo:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (App.returnPage)
{
App.returnPage = false;
NavigationContext.QueryString.TryGetValue("id", out navId);
NavigationService.GoBack();
}
else if (e.NavigationMode != NavigationMode.Reset)
{
// normal navigation
}
}
It works like this:
when you launch normally your App, returnPage is false, everything goes normal
when you activate it from secondary tile few things happen:
1. first goes navigation to your previous page with NavigationMode.Reset - we are not interested in it, so I switched it off - nothing should happen
2. then program tries to create new instance of MainPage, but returnPage is true, and because of the if statement, InitializeComponent won't run. Just after this, in OnNavigatedTo, program saves passed querystring and Navigates Back to previous instance of MainPage - from previous run
3. at last we are navigating to right MainPage with NavigationMode.Back and we have our querystring saved in static variable.
You must be aware of two things: first - probably it can be little rebuild (I'm not sure if wasRelaunched is needed and so on) - you need to debug it and see of what you can get rid off. Second - you will probably need to test your App with Tombstone case.
Hope this helps.