Search Results

Search found 266 results on 11 pages for 'nullreferenceexception'.

Page 9/11 | < Previous Page | 5 6 7 8 9 10 11  | Next Page >

  • PostSharp when using DataContractSerializer?

    - by Dan Bryant
    I have an Aspect that implements INotifyPropertyChanged on a class. The aspect includes the following: [OnLocationSetValueAdvice, MethodPointcut("SelectProperties")] public void OnPropertySet(LocationInterceptionArgs args) { var currentValue = args.GetCurrentValue(); bool alreadyEqual = (currentValue == args.Value); // Call the setter args.ProceedSetValue(); // Invoke method OnPropertyChanged (ours, the base one, or the overridden one). if (!alreadyEqual) OnPropertyChangedMethod.Invoke(args.Location.Name); } This works fine when I instantiate the class normally, but I run into problems when I deserialize the class using a DataContractSerializer. This bypasses the constructor, which I'm guessing interferes with the way that PostSharp sets itself up. This ends up causing a NullReferenceException in an intercepted property setter, but before it has called the custom OnPropertySet, so I'm guessing it interferes with setting up the LocationInterceptionArgs. Has anyone else encountered this problem? Is there a way I can work around it? I did some more research and discovered I can fix the issue by doing this: [OnDeserializing] private void OnDeserializing(StreamingContext context) { AspectUtilities.InitializeCurrentAspects(); } I thought, okay, that's not too bad, so I tried to do this in my Aspect: private IEnumerable<MethodInfo> SelectDeserializing(Type type) { return type.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).Where( t => t.IsDefined(typeof (OnDeserializingAttribute), false)); } [OnMethodEntryAdvice, MethodPointcut("SelectDeserializing")] public void OnMethodEntry(MethodExecutionArgs args) { AspectUtilities.InitializeCurrentAspects(); } Unfortunately, even though it intercepts the method properly, it doesn't work. I'm thinking the call to InitializeCurrentAspects isn't getting transformed properly, since it's now inside the Aspect rather than directly inside the aspect-enhanced class. Is there a way I can cleanly automate this so that I don't have to worry about calling this on every class that I want to have the Aspect?

    Read the article

  • Matlab and .net problem with character string function input

    - by Peter
    I have a MATLAB function that I've compiled into a .net library. The function is a simple one that takes a character array as an input and a numeric array as output: function insert = money(dateLimit) .. insert = [1 2]; The function works fine when no function arguments are specified (a default argument is provided inside the function) Dim sf As New SpreadFinder.SpreadFinder Dim output = sf.money() As soon as an argument is specified .net complains. I'm thinking this should be easy and has been done before but searching through MATLAB documentation doesn't offer much help. Here's what I've tried. The sf.money() overload for the function with arguments is (numArgsOut as Integer, argsOut as MWArray, argsIn as MWArray) and hence that's what I've tried. What am I missing? Dim sf As New SpreadFinder.SpreadFinder Dim inputArgs(1) As Arrays.MWCharArray Dim dateLimitString As String = "some string" inputArgs(0) = New Arrays.MWCharArray(dateLimitString) Dim outputArgs(1) As Arrays.MWNumericArray outputArgs(0) = New Arrays.MWNumericArray() sf.money(1, outputArgs, inputArgs) Gives System.NullReferenceException : Object reference not set to an instance of an object. at MathWorks.MATLAB.NET.Utility.MWMCR.EvaluateFunction(String functionName, Int32 numArgsOut, Int32 numArgsIn, MWArray[] argsIn) at MathWorks.MATLAB.NET.Utility.MWMCR.EvaluateFunction(String functionName, Int32 numArgsOut, MWArray[]& argsOut, MWArray[] argsIn) at SpreadFinder.SpreadFinder.money(Int32 numArgsOut, MWArray[]& argsOut, MWArray[] argsIn)

    Read the article

  • How can I use System.Web.Caching.Cache in a Console application?

    - by Ron Klein
    Context: .Net 3.5, C# I'd like to have caching mechanism in my Console application. Instead of re-inventing the wheel, I'd like to use System.Web.Caching.Cache (and that's a final decision, I can't use other caching framework, don't ask why). However, it looks like System.Web.Caching.Cache is supposed to run only in a valid HTTP context. My very simple snippet looks like this: using System; using System.Web.Caching; using System.Web; Cache c = new Cache(); try { c.Insert("a", 123); } catch (Exception ex) { Console.WriteLine("cannot insert to cache, exception:"); Console.WriteLine(ex); } and the result is: cannot insert to cache, exception: System.NullReferenceException: Object reference not set to an instance of an object. at System.Web.Caching.Cache.Insert(String key, Object value) at MyClass.RunSnippet() So obviously, I'm doing something wrong here. Any ideas? Update: +1 to most answers, getting the cache via static methods is the correct usage, namely HttpRuntime.Cache and HttpContext.Current.Cache. Thank you all!

    Read the article

  • The uncatchable exception

    - by chaiguy
    Another custom MarkupExtension binding question... This time, my converter is being called before DataContext is set on the target element. This isn't a big deal because it will get updated when DataContext eventually receives a value. What is causing problems is the NullReferenceException I'm getting because of DataContext being null. Even though I'm attempting to catch the exception in my value converter: try { return ( (MethodInfo)_member ).Invoke( parameter, null ); } catch { return Binding.DoNothing; } For some reason the debugger is still halting at this point. Now I'm thinking it could be because the exception is happening in another assembly from where it is being caught (I'm trying to package this in a reusable class library, and _member above points to a method in the application assembly). If I run my little test app without the debugger it works fine, however my application is a little more robust and has general exception handling which is getting triggered because of this. I'm wondering if there is just some attribute or something (or perhaps some reflection parameter I'm missing?) I can use to make the exception be caught like it's supposed to.

    Read the article

  • Intercepting hyperlinks in an embedded Word document

    - by Ryan
    Hello, I'm working on an app which uses embedded Word documents. We have a feature which allows them to insert a small clickable image into the doc - when the user clicks on it, we want the app to open another window based on some data specified by the user when the image was added. What the application does now is: When the image is inserted, the app creates a hyperlink for it and the data is used as the link destination The user ctrl+clicks on the image and the Word document the WindowSelectionChange event The app handles the WindowSelectionChange event and goes to open the specified window This approach worked fine with previous versions, when we had the 11.0 / Word 2003 interop dll's. We upgraded to 12.0/Word 2007 for the upcoming release, and in many cases the event is not firing when I click on the image - sometimes it does, sometimes it doesn't, and I'm descending into the cargo-cult world trying to figure out why - sometimes saving and re-opening the document works, sometimes killing the Word process and starting a new one fixes (or breaks) the feature. My guess is there's something going wrong with the WinSelChg event, but I'm not sure what. The usual process we have for applying the event handler is: try //remove the old one if any { ((Document)myAXFramerControl.ActiveDocument).Application.WindowSelectionChange -= new ApplicationEvents4_WindowSelectionChangeEventHandler(WSC_eventhandlerfunction); } catch{} ((Document)myAXFramerControl.ActiveDocument).Application.WindowSelectionChange += new ApplicationEvents4_WindowSelectionChangeEventHandler(WSC_eventhandlerfunction); Sometimes one or both of these will throw exceptions - usually a NullReferenceException when removing the handler. Adding the handler sometimes throws the "com object that has been separated from its underlying rcw cannot be used" exception, which I don't understand at all - my impression was that this only occurs when you, say, store a reference to the Word application or document and try to use it later. As it stands the WSC event handler is frequently never run; while I'm happy to fiddle with the app until it works once I can't really expect the same of the users who have been happily using this feature for a while now. Any ideas?

    Read the article

  • Unit Testing (xUnit) an ASP.NET Mvc Controller with a custom input model?

    - by Danny Douglass
    I'm having a hard time finding information on what I expect to be a pretty straightforward scenario. I'm trying to unit test an Action on my ASP.NET Mvc 2 Controller that utilizes a custom input model w/ DataAnnotions. My testing framework is xUnit, as mentioned in the title. Here is my custom Input Model: public class EnterPasswordInputModel { [Required(ErrorMessage = "")] public string Username { get; set; } [Required(ErrorMessage = "Password is a required field.")] public string Password { get; set; } } And here is my Controller (took out some logic to simplify for this ex.): [HttpPost] public ActionResult EnterPassword(EnterPasswordInputModel enterPasswordInput) { if (!ModelState.IsValid) return View(); // do some logic to validate input // if valid - next View on successful validation return View("NextViewName"); // else - add and display error on current view return View(); } And here is my xUnit Fact (also simplified): [Fact] public void EnterPassword_WithValidInput_ReturnsNextView() { // Arrange var controller = CreateLoginController(userService.Object); // Act var result = controller.EnterPassword( new EnterPasswordInputModel { Username = username, Password = password }) as ViewResult; // Assert Assert.Equal("NextViewName", result.ViewName); } When I run my test I get the following error on my test fact when trying to retrieve the controller result (Act section): System.NullReferenceException: Object reference not set to an instance of an object. Thanks in advance for any help you can offer!

    Read the article

  • Entity Framework 4 overwrite Equals and GetHashCode of an own class property

    - by Zhok
    Hi, I’m using Visual Studio 2010 with .NET 4 and Entity Framework 4. I’m working with POCO Classes and not the EF4 Generator. I need to overwrite the Equals() and GetHashCode() Method but that doesn’t really work. Thought it’s something everybody does but I don’t find anything about the problem Online. When I write my own Classes and Equals Method, I use Equals() of property’s, witch need to be loaded by EF to be filled. Like this: public class Item { public virtual int Id { get; set; } public virtual String Name { get; set; } public virtual List<UserItem> UserItems { get; set; } public virtual ItemType ItemType { get; set; } public override bool Equals(object obj) { Item item = obj as Item; if (obj == null) { return false; } return item.Name.Equals(this.Name) && item.ItemType.Equals(this.ItemType); } public override int GetHashCode() { return this.Name.GetHashCode() ^ this.ItemType.GetHashCode(); } } That Code doesn’t work, the problems are in Equals and GetHashCode where I try to get HashCode or Equal from “ItemType” . Every time I get a NullRefernceException if I try to get data by Linq2Entites. A dirty way to fix it, is to capture the NullReferenceException and return false (by Equals) and return base.GetHashCode() (by GethashCode) but I hope there is a better way to fix this problem. I’ve wrote a little test project, with SQL Script for the DB and POCO Domain, EDMX File and Console Test Main Method. You can download it here: Download

    Read the article

  • Error with Property Validation in Form Submission in ASP.NET MVC

    - by Maxim Z.
    I have a simple form on an ASP.NET MVC site that I'm building. This form is submitted, and then I validate that the form fields aren't null, empty, or improperly formatted. However, when I use ModelState.AddModelError() to indicate validation errors from my controller code, I get an error when my view is re-rendered. In Visual Studio, I get that the following line is highlighted as being the location of the error: <%=Html.TextBox("Email")%> The error is the following: NullReferenceException was unhandled by user code - object reference not set to an instance of an object. My complete code for that textbox is the following: <p> <label for="Email">Your Email:</label> <%=Html.TextBox("Email")%> <%=Html.ValidationMessage("Email", "*") %> </p> Here's how I'm doing that validation in my controller: try { System.Net.Mail.MailAddress address = new System.Net.Mail.MailAddress(email); } catch { ModelState.AddModelError("Email", "Should not be empty or invalid"); } return View(); Note: this applies to all of my fields, not just my Email field, as long as they are invalid.

    Read the article

  • Cookie add in the Global.asax warning in application log

    - by Ioxp
    In my Global.ASAX file i have the following: System.Web.HttpCookie isAccess = new System.Web.HttpCookie("IsAccess"); isAccess.Expires = DateTime.Now.AddDays(-1); isAccess.Value = ""; System.Web.HttpContext.Current.Response.Cookies.Add(isAccess); So every time this method this is logged in the application events as a warning: Event code: 3005 Event message: An unhandled exception has occurred. Event time: 5/25/2010 12:23:20 PM Event time (UTC): 5/25/2010 4:23:20 PM Event ID: c515e27a28474eab8d99720c3f5a8e90 Event sequence: 4148 Event occurrence: 332 Event detail code: 0 Application information: Application domain: /LM/W3SVC/2100509645/Root-1-129192259222289896 Trust level: Full Application Virtual Path: / Application Path: <PathRemoved>\www\ Machine name: TIPPER Process information: Process ID: 6936 Process name: w3wp.exe Account name: NT AUTHORITY\NETWORK SERVICE Exception information: Exception type: NullReferenceException Exception message: Object reference not set to an instance of an object. Request information: Request URL: Request path: User host address: User: Is authenticated: False Authentication Type: Thread account name: NT AUTHORITY\NETWORK SERVICE Thread information: Thread ID: 7 Thread account name: NT AUTHORITY\NETWORK SERVICE Is impersonating: False Stack trace: at ASP.global_asax.Session_End(Object sender, EventArgs e) in <PathRemoved>\Global.asax:line 113 Any idea why this code would cause this error?

    Read the article

  • Null reference exceptions in .net

    - by Carlo
    Hello, we're having this big problem with our application. It's a rather large application with several modules, and thousands and thousands lines of code. A lot of parts of the application are designed to exist only with a reference to another object, for example a Person object can never exists without a House object, so if you at any point in the app say: bool check = App.Person.House == null; check should always be false (by design), so, to keep using that example, while creating modules, testing, debugging, App.Person.House is never null, but once we shipped the application to our client, they started getting a bunch of NullReferenceException with the objects that by design, should never have a null reference. They tell us the bug, we try to reproduce it here, but 90% of the times we can't, because here it works fine. The app is being developed with C# and WPF, and by design, it only runs on Windows XP SP 3, and the .net framework v3.5, so we KNOW the user has the same operative system, service pack, and .net framework version as we do here, but they still get this weird NullReferenceExceptions that we can't reproduce. So, I'm just wondering if anyone has seen this before and how you fixed it, we have the app running here at least 8 hours a day in 5 different computers, and we never see those exceptions, this only happens to the client for some reason. ANY thought, any clue, any solution that could get us closer to fixing this problem will be greatly appreciated. Thanks!

    Read the article

  • Rhinomocks DynamicMock question

    - by epitka
    My dynamic mock behaves as Parial mock, meaning it executes the actual code when called. Here are the ways I tried it var mockProposal = _mockRepository.DynamicMock<BidProposal>(); SetupResult.For(mockProposal.CreateMarketingPlan(null, null, null)).IgnoreArguments().Repeat.Once().Return( copyPlan); //Expect.Call(mockProposal.CreateMarketingPlan(null, null, null)).IgnoreArguments().Repeat.Once().Return( // copyPlan); // mockProposal.Expect(x => x.CreateMarketingPlan(null, null, null)).IgnoreArguments().Return(copyPlan).Repeat.Once(); Instead of just returning what I expect it runs the code in the method CreateMarketingPlan Here is the error: System.NullReferenceException: Object reference not set to an instance of an object. at Policy.Entities.MarketingPlan.SetMarketingPlanName(MarketingPlanDescription description) in MarketingPlan.cs: line 76 at Policy.Entities.MarketingPlan.set_MarketingPlanDescription(MarketingPlanDescription value) in MarketingPlan.cs: line 91 at Policy.Entities.MarketingPlan.Create(PPOBenefits ppoBenefits, MarketingPlanDescription marketingPlanDescription, MarketingPlanType marketingPlanType) in MarketingPlan.cs: line 23 at Policy.Entities.BidProposal.CreateMarketingPlan(PPOBenefits ppoBenefits, MarketingPlanDescription marketingPlanDescription, MarketingPlanType marketingPlanType) in BidProposal.cs: line 449 at Tests.Policy.Services.MarketingPlanCopyServiceTests.can_copy_MarketingPlan_with_all_options() in MarketingPlanCopyServiceTests.cs: line 32 Update: I figured out what it was. Method was not "virtual" so it could not be mocked because non-virtual methods cannot be proxied.

    Read the article

  • How to: generate UnhandledException?

    - by serhio
    I use this code to catch the WinForm application UnhandledException. [STAThread] static void Main(string[] args) { // Add the event handler for handling UI thread exceptions to the event. Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); // Set the unhandled exception mode to force all Windows Forms errors // to go through our handler. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); // Add the event handler for handling non-UI thread exceptions to the event. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); try { Application.Run(new MainForm()); } catch.... There I will try to restart the application. Now my problem is to simulate a exception like this. I tried before try (in main): throw new NullReferenceException("test"); VS caught it. Tried also in MainForm code with button : private void button1_Click(object sender, EventArgs ev) { ThreadPool.QueueUserWorkItem(new WaitCallback(TestMe), null); } protected void TestMe(object state) { string s = state.ToString(); } did not help, VS caught it, even in Release mode. How should I, finally, force the application generate UnhandleldException? Will I be able to restart the application in CurrentDomain_UnhandledException?

    Read the article

  • Visual Studio Unit Test failure to start

    - by swmi
    Hi, I am having an issue when starting the tests under debug mode in Visual Studio 2008 Team Test where it gives the following error: "Failed to queue test run '{user@machinename}': Object reference not set to an instance of an object." I googled for the error but no joy. Don't even understand what it means as it is too brief. Has anyone come across this? Note that I can run tests fine if I am not debugging and I get the same error irrespective of the test I run. Thank you, Swati ETA: Being new to Visual Studio Team Test, I didn't know there was a better exception log then what I was seeing. Anyhow, here it is: <Exception> System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.VisualStudio.TestTools.TestCaseManagement.QualityToolsPackage. ShowToolWindow [T](T&amp; toolWindow, String errorMessage, Boolean show) at Microsoft.VisualStudio.TestTools.TestCaseManagement.QualityToolsPackage. OpenTestResultsToolWindow() at Microsoft.VisualStudio.TestTools.TestCaseManagement.SolutionIntegrationManager. DebugTarget(DebugInfo debugInfo, Boolean prepareEnvironment) at Microsoft.VisualStudio.TestTools.TestManagement.DebugProcessLauncher.Launch( String exeFileName, String args, String workingDir, EventHandler processExitedHandler, Process&amp; process) at Microsoft.VisualStudio.TestTools.TestManagement.LocalControllerProxy.StartProcess( TestRun run) at Microsoft.VisualStudio.TestTools.TestManagement.LocalControllerProxy.RestartProcess( TestRun run) at Microsoft.VisualStudio.TestTools.TestManagement.LocalControllerProxy.PrepareProcess( TestRun run) at Microsoft.VisualStudio.TestTools.TestManagement.LocalControllerProxy. InitializeController(TestRun run) at Microsoft.VisualStudio.TestTools.TestManagement.ControllerProxy.QueueTestRunWorker( Object state) </Exception>

    Read the article

  • c#3.5 Deserialization error - object reference not set

    - by BBR
    I am trying to deserialize an xml string in c#3.5, the code below does work in c# 4.0. When I try to run in the code in c#3.5 I get an Object reference not set to an instance of an object exception when the code tries in initialize the XmlSerializer. Any help would be appreciated. string xml = "<boolean xmlns=\"http://schemas.microsoft.com/2003/10/serialization/\">false</boolean>"; var xSerializer = new XmlSerializer(typeof(bool), null, null, new XmlRootAttribute("boolean"), "http://schemas.microsoft.com/2003/10/serialization/"); using (var sr = new StringReader(xml)) using (var xr = XmlReader.Create(sr)) { var y = xSerializer.Deserialize(xr); } System.NullReferenceException was unhandled Message="Object reference not set to an instance of an object." Source="System.Xml" StackTrace: at System.Xml.Serialization.XmlSerializer..ctor(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, String defaultNamespace, String location, Evidence evidence) at System.Xml.Serialization.XmlSerializer..ctor(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, String defaultNamespace) .... at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException:

    Read the article

  • CCNet exception during build of vs2010 project

    - by sonee
    We have two build machines. Lately, we've migrated our projects to vs2010 from vs2005. But the problem is that one of the machines occurs error during build. Another machine works well, but just one machine shows error. The differences between the machines are os and computer spec. The machine which is working well is installed windows server 2003 and the other is windows7. the error message is unhandled exception: System.NullReferenceException: Microsoft.VisualStudio.Shell.ThreadHelper.InvokeOnUIThread(InvokableBase invokable) Microsoft.VisualStudio.Shell.ThreadHelper.Invoke(Action action)Microsoft.VisualStudio.Project.VS.Implementation.VSShellServices.InvokeOnUIThread(Action method) Microsoft.VisualStudio.Project.VisualC.VCProjectEngine.ApartmentMarshaler.Invoke(Action method) Microsoft.VisualStudio.Project.VisualC.VCProjectEngine.VCConfigBuildJob.BuildCompleted(BuildSubmission ar) Microsoft.VisualStudio.Project.Contracts.Implementation.BuildProjectBase.BuildCompletedCallbackManager.BuildCompleted(BuildSubmission buildSubmission) Microsoft.Build.Execution.BuildSubmission.<CheckForCompletion>b__0(Object state) System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state) System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() System.Threading.ThreadPoolWorkQueue.Dispatch() System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() Curiously enough, when I run building project in command line on the machine which occurs error, it works well. The machine just shows error when launched by ccnet. I've installed latest version of ccnet to all machines. Is there anybody who faced like this problem?

    Read the article

  • wpf observableCollection

    - by Asha
    I have an ObservableCollection which is dataContext for my treeview when I try to remove an Item from ObservableCollection I will get an error that Object reference not set to an instance of an object . can you please tell me why this error is happening and what is the solution thanks EDIT 1: The code is something like : class MyClass : INotifyPropertyChanged { //my class code here } public partial class UC_myUserControl : UserControl { private ObservableCollection<MyClass> myCollection = new ObservableCollection<MyClass>(); private void UserControl_Loaded(object sender, RoutedEventArgs e) { myCollection.add(new myClass); myTreeView.DataContext = myCollection ; } private void deleteItem() { myCollection.RemoveAt(0); //after removing I get error Which I guess should be something related //to interface update but I don't know how can I solve it } } Exception Detail : System.NullReferenceException was unhandled Message="Object reference not set to an instance of an object." Source="PresentationFramework" EDIT 3: I have a style which is for my treeitem to keep the treeitems expanded <Style TargetType="TreeViewItem"> <Setter Property="IsExpanded" Value="True" /> </Style> and with commenting this part I wont get any error !!! Now I want to change my question to why having this style is causing error ?

    Read the article

  • Adding an ASP.NET Web User Control to a Control Dynamically

    - by RandomBen
    I have a simple ASP.NET Web User Control. It looks like this: <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="NewsArticle.ascx.cs" Inherits="Website.Controls.NewsArticle" %> <div> <asp:Literal ID="ltlBody" runat="server" /> </div> My code behind looks like this: namespace Website.Controls { public partial class NewsArticle : System.Web.UI.UserControl { public String bodyText { //get { return ltlBody.Text; } set { ltlBody.Text = value; } } } } On a .aspx page I have <asp:Panel ID="pNews" runat="server" /> In the code behind I have: foreach (vwNews news in newsQuery) { NewsArticle article = new NewsArticle(); aticle.bodyText = news.Body; pNews.Controls.Add(article); } Every time I run this code the newsQuery is populated correctly and I get to the line aticle.bodyText = news.Body; and then I received the error article.bodyText threw an exception of type 'System.NullReferenceException' I am not sure what is causing this error message or how to fix it. I would think that there should not be an issue. I tried creating a constructor for my Web User Control so that it would give default values to my properties but that didn't work. Any idea how to make this work? It doesn't seem like it should be that

    Read the article

  • C# Minimize all running windows when application runs

    - by Derek
    I am working on a C# windows form application. How can i edit my code in a way that when more than 2 faces is being detected by my webcam. More information: When "FaceDetectedLabel.Text = "Faces Detected : " + cam.facesdetected.ToString();" becomes Face Detected: 2 or more... How can i do the following: Minimize all program running except my application. Log out of my computer Here is my code: namespace PBD { public partial class MainPage : Form { //declaring global variables private Capture capture; //takes images from camera as image frames public MainPage() { InitializeComponent(); } private void ProcessFrame(object sender, EventArgs arg) { Wrapper cam = new Wrapper(); //show the image in the EmguCV ImageBox WebcamPictureBox.Image = cam.start_cam(capture).Resize(390, 243, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC).ToBitmap(); FaceDetectedLabel.Text = "Faces Detected : " + cam.facesdetected.ToString(); } private void MainPage_Load(object sender, EventArgs e) { #region if capture is not created, create it now if (capture == null) { try { capture = new Capture(); } catch (NullReferenceException excpt) { MessageBox.Show(excpt.Message); } } #endregion Application.Idle += ProcessFrame; }

    Read the article

  • ASP.NEt MVC 2 application error on IIS7 works fine on local machine

    - by aspCoolguy
    My ASP.NET MVC2 application is developed using 1. VS 2010 2. Linq To SQL for Models Here is Call controller code: namespace CallTrackMVC.Controllers { public class CallController : Controller { private CallTrackRepository repository; public CallController():this(new CallTrackRepository()) { } public CallController(CallTrackRepository newRepository) { repository = newRepository; } } } Error on IIS7 when browsing the Call Create page is NullReferenceException: Object reference not set to an instance of an object.] CallTrackMVC.Models.ExecOfficeDataContext..ctor() in C:\ClearCase\rartadi_view\STS_Dev_TEST\CallTrackMVC\Models\ExecOffice.designer.cs:71 CallTrackMVC.Controllers.CallController..ctor() in C:\ClearCase\rartadi_view\STS_Dev_TEST\CallTrackMVC\Controllers\CallController.cs:16 [TargetInvocationException: Exception has been thrown by the target of an invocation.] System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0 System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +117 System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +247 System.Activator.CreateInstance(Type type, Boolean nonPublic) +106 System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +102 [InvalidOperationException: **An error occurred when trying to create a controller of type 'CallTrackMVC.Controllers.CallController'. Make sure that the controller has a parameterless public constructor.**] System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +541 System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +85 System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +165 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +80 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +389 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +371 Code in Global.asax is protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); } Any suggestion would be a great help.

    Read the article

  • Proper way to scan a range of IP addresses

    - by Josh G
    Given a range of IP addresses entered by a user (through various means), I want to identify which of these machines have software running that I can talk to. Here's the basic process: Ping these addresses to find available machines Connect to a known socket on the available machines Send a message to the successfully established sockets Compare the response to the expected response Steps 2-4 are straight forward for me. What is the best way to implement the first step in .NET? I'm looking at the System.Net.NetworkInformation.Ping class. Should I ping multiple addresses simultaneously to speed up the process? If I ping one address at a time with a long timeout it could take forever. But with a small timeout, I may miss some machines that are available. Sometimes pings appear to be failing even when I know that the address points to an active machine. Do I need to ping twice in the event of the request getting discarded? To top it all off, when I scan large collections of addresses with the network cable unplugged, Ping throws a NullReferenceException in FreeUnmanagedResources(). !? Any pointers on the best approach to scanning a range of IPs like this?

    Read the article

  • Cant insert a object into a silverlight databound combo box

    - by Steve
    Hi Until recently I had a combo box that was bound to a Linq queried IEnumerable of a DataService.Obj type in the bind method, and all worked fine private IEnumerable<DataService.Obj> _GeneralList; private IEnumerable<DataService.Obj> _QueriedList; private void Bind() { _GeneralList = SharedLists.GeneralList; _QueriedList = _GeneralList.Where(q =>q.ID >1000); cmbobox.ItemsSource = _QueriedList; } Then I had to change the method to insert a new obj and set that object as the default obj and now I get a "System.NullReferenceException: Object reference not set to an instance of an object" exception. I know this has to do with inserting into a linq queried ienumerable but I cant fix it. Any help will be gratefully received. private IEnumerable<DataService.Obj> _GeneralList; private IEnumerable<DataService.Obj> _QueriedList; private void Bind() { _GeneralList = SharedLists.GeneralList; _QueriedList = _GeneralList.Where(q =>q.ID >1000); cmbobox.ItemsSource = _QueriedList; DataService.Obj info = new DataService.Obj(); info.ID = "0"; (cmbobox.ItemsSource as ObservableCollection<DataService.Obj>).Insert(0,info); cmbobox.SelectedIndex = 0; } Thanks in advance

    Read the article

  • C# Virtual method call in constructor - how to refactor?

    - by Cristi Diaconescu
    I have an abstract class for database-agnostic cursor actions. Derived from that, there are classes that implement the abstract methods for handling database-specific stuff. The problem is, the base class ctor needs to call an abstract method - when the ctor is called, it needs to initialize the database-specific cursor. I know why this shouldn't be done, I don't need that explanation! This is my first implementation, that obviously doesn't work - it's the textbook "wrong way" of doing it. The overridden method accesses a field from the derived class, which is not yet instantiated: public abstract class CursorReader { private readonly int m_rowCount; protected CursorReader() { m_rowCount = CreateCursor(sqlCmd); //virtual call ! } protected abstract int CreateCursor(string sqlCmd); } public class SqlCursorReader : CursorReader { private SqlConnection m_sqlConnection; public SqlCursorReader(string sqlCmd, SqlConnection sqlConnection) { m_sqlConnection = sqlConnection; //field initialized here } protected override int CreateCursor(string sqlCmd) { //uses not-yet-initialized member *m_sqlConnection* //so this throws a NullReferenceException var cursor = new CustomCursor(sqlCmd, m_sqlConnection); return cursor.Count(); } } I will follow up with an answer on my attempts to fix this...

    Read the article

  • Lucene.Net: How can I add a date filter to my search results?

    - by rockinthesixstring
    I've got my searcher working really well, however it does tend to return results that are obsolete. My site is much like NerdDinner whereby events in the past become irrelevant. I'm currently indexing like this Public Function AddIndex(ByVal searchableEvent As [Event]) As Boolean Implements ILuceneService.AddIndex Dim writer As New IndexWriter(luceneDirectory, New StandardAnalyzer(), False) Dim doc As Document = New Document doc.Add(New Field("id", searchableEvent.ID, Field.Store.YES, Field.Index.UN_TOKENIZED)) doc.Add(New Field("fullText", FullTextBuilder(searchableEvent), Field.Store.YES, Field.Index.TOKENIZED)) doc.Add(New Field("user", If(searchableEvent.User.UserName = Nothing, "User" & searchableEvent.User.ID, searchableEvent.User.UserName), Field.Store.YES, Field.Index.TOKENIZED)) doc.Add(New Field("title", searchableEvent.Title, Field.Store.YES, Field.Index.TOKENIZED)) doc.Add(New Field("location", searchableEvent.Location.Name, Field.Store.YES, Field.Index.TOKENIZED)) doc.Add(New Field("date", searchableEvent.EventDate, Field.Store.YES, Field.Index.UN_TOKENIZED)) writer.AddDocument(doc) writer.Optimize() writer.Close() Return True End Function Notice how I have a "date" index that stores the event date. My search then looks like this ''# code omitted Dim reader As IndexReader = IndexReader.Open(luceneDirectory) Dim searcher As IndexSearcher = New IndexSearcher(reader) Dim parser As QueryParser = New QueryParser("fullText", New StandardAnalyzer()) Dim query As Query = parser.Parse(q.ToLower) ''# We're using 10,000 as the maximum number of results to return ''# because I have a feeling that we'll never reach that full amount ''# anyways. And if we do, who in their right mind is going to page ''# through all of the results? Dim topDocs As TopDocs = searcher.Search(query, Nothing, 10000) Dim doc As Document = Nothing ''# loop through the topDocs and grab the appropriate 10 results based ''# on the submitted page number While i <= last AndAlso i < topDocs.totalHits doc = searcher.Doc(topDocs.scoreDocs(i).doc) IDList.Add(doc.[Get]("id")) i += 1 End While ''# code omitted I did try the following, but it was to no avail (threw a NullReferenceException). While i <= last AndAlso i < topDocs.totalHits If Date.Parse(doc.[Get]("date")) >= Date.Today Then doc = searcher.Doc(topDocs.scoreDocs(i).doc) IDList.Add(doc.[Get]("id")) i += 1 End If End While I also found the following documentation, but I can't make heads or tails of it http://lucene.apache.org/java/1_4_3/api/org/apache/lucene/search/DateFilter.html

    Read the article

  • Can this line of code really throw an IndexOutOfRange exception?

    - by Jonathan M
    I am getting an IndexOutOfRange exception on the following line of code: var searchLastCriteria = (SearchCriteria)Session.GetSafely(WebConstants.KeyNames.SEARCH_LAST_CRITERIA); I'll explain the above here: SearchCriteria is an Enum with only two values Session is the HttpSessionState GetSafely is an extension method that looks like this: public static object GetSafely(this HttpSessionState source, string key) { try { return source[key]; } catch (Exception exc) { log.Info(exc); return null; } } WebConstants.KeyNames.SEARCH_LAST_CRITERIA is simply a constant I've tried everything to replicate this error, but I cannot reproduce it. I am beginning to think the stack trace is wrong. I thought perhaps the exception was actually coming from the GetSafely call, but it is swallowing the exceptions, so that can't be the case, and even if it was, it should show up in the stack trace. Is there anything in the line of code above that could possible throw an IndexOutOfRange exception? I know the line will throw an NullReferenceException if GetSafely returns null, and it will also throw an InvalidCastException if it returns anything that cannot be cast to SearchCriteria, but an IndexOutOfRange exception? I'm scratching my head here. Here is the stack trace: $LOG--> 2010-06-11 07:01:33,814 [ERROR] SERVERA (14) Web.Global - Index was outside the bounds of the array. System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.IndexOutOfRangeException: Index was outside the bounds of the array. at IterateSearchResult(Boolean next) in C:\Projects\Web\UserControls\AccountHeader.ascx.cs:line 242 at nextAccountLink_Click(Object sender, EventArgs e) in C:\Projects\Web\UserControls\AccountHeader.ascx.cs:line 232

    Read the article

  • How to Object Array to List

    - by Peter Black
    (C#) I have 2 classes. 1 is called Employee. The other is my "main". I am trying to take a list and assign each value in list to an array of Employee object. //Inside "Main" class int counter = NameList.Count; Employee[] employee = new Employee[counter]; for (int i = 0; i <= counter; i++) { employee[i].Name = NameList[i]; employee[i].EmpNumber = EmpNumList[i]; employee[i].DateOfHire = DOHList[i]; employee[i].Salary = SalaryList[i]; employee[i].JobDescription = JobDescList[i]; employee[i].Department = DeptList[i]; } This returns the error: An unhandled exception of type 'System.NullReferenceException' occurred in Pgm4.exe Additional information: Object reference not set to an instance of an object. I think this means that I am not calling the list properly. Any help would be much appreciated. Thank you.

    Read the article

< Previous Page | 5 6 7 8 9 10 11  | Next Page >