Search Results

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

Page 1/11 | 1 2 3 4 5 6 7 8 9 10 11  | Next Page >

  • What is a NullReferenceException in .NET?

    - by John Saunders
    (I'm creating this separate question and answer because every question we get on NullReferenceException is really the same) I have some code and when it executes, it throws a NullReferenceException, saying, "Object reference not set to an instance of an object.". What does this mean, and what can I do about it? Note again, that this is a question meant to focus answers to the canonical "what is a NullReferenceException and why did I get one" question. I do know what a NullReferenceException is, as my answer below demonstrates.

    Read the article

  • .NET - Very strange NullReferenceException?

    - by ropstah
    How can I get a NullReferenceException in the following scenario? Dim langs As IEnumerable(Of SomeCustomObject) = //some LINQ query If langs Is Nothing Then Return Nothing If langs.Count = 1 Then //NullReferenceException here What am I missing here? Debug shows that langs is really just a LINQ queryresult without any results...

    Read the article

  • NullReferenceException when initializing NServiceBus within web application Application_Start method

    - by SteveBering
    I am running the 2.0 RTM of NServiceBus and am getting a NullReferenceException when my MessageModule binds the CurrentSessionContext to my NHibernate sessionfactory. From within my Application_Start, I call the following method: public static void WithWeb(IUnityContainer container) { log4net.Config.XmlConfigurator.Configure(); var childContainer = container.CreateChildContainer(); childContainer.RegisterInstance<ISessionFactory>(NHibernateSession.SessionFactory); var bus = NServiceBus.Configure.WithWeb() .UnityBuilder(childContainer) .Log4Net() .XmlSerializer() .MsmqTransport() .IsTransactional(true) .PurgeOnStartup(false) .UnicastBus() .ImpersonateSender(false) .LoadMessageHandlers() .CreateBus(); var activeBus = bus.Start(); container.RegisterInstance(typeof(IBus), activeBus); } When the bus is started, my message module starts with the following: public void HandleBeginMessage() { try { CurrentSessionContext.Bind(_sessionFactory.OpenSession()); } catch (Exception e) { _log.Error("Error occurred in HandleBeginMessage of NHibernateMessageModule", e); throw; } } In looking at my log, we are logging the following error when the bind method is called: System.NullReferenceException: Object reference not set to an instance of an object. at NHibernate.Context.WebSessionContext.GetMap() at NHibernate.Context.MapBasedSessionContext.set_Session(ISession value) at NHibernate.Context.CurrentSessionContext.Bind(ISession session) Apparently, there is some issue in getting access to the HttpContext. Should this call to configure NServiceBus occur later in the lifecycle than Application_Start? Or is there another workaround that others have used to get handlers working within an Asp.NET Web application? Thanks, Steve

    Read the article

  • C# NullReferenceException when passing DataTable

    - by Timothy
    I've been struggling with a NullReferenceException and hope someone here will be able to point me in the right direction. I'm trying to create and populate a DataTable and then show the results in a DataGridView control. The basic code follows, and Execution stops with a NullReferenceException at the point where I invoke the new UpdateResults_Delegate. Oddly enough, I can trace entries.Rows.Count successfully before I return it from QueryEventEntries, so I can at least show 1) entries is not a null reference, and 2) the DataTable contains rows of data. I know I have to be doing something wrong, but I just don't know what. private delegate void UpdateResults_Delegate(DataTable entries); private void UpdateResults(DataTable entries) { dataGridView.DataSource = entries; } private void button_Click(object sender, EventArgs e) { Thread t = new Thread(new ThreadStart(PerformQuery)); t.Start(); } private void PerformQuery() { DateTime start = new DateTime(dateTimePicker1.Value.Year, dateTimePicker1.Value.Month, dateTimePicker1.Value.Day, 0, 0, 0); DateTime stop = new DateTime(dateTimePicker2.Value.Year, dateTimePicker2.Value.Month, dateTimePicker2.Value.Day, 0, 0, 0); DataTable entries = QueryEventEntries(start, stop); Invoke(new UpdateResults_Delegate(UpdateResults), entries); } private DataTable QueryEventEntries(DateTime start, DateTime stop) { DataTable entries = new DataTable(); entries.Columns.Add("colEventType", typeof(Int32)); entries.Columns.Add("colTimestamp", typeof(Int32)); entries.Columns.Add("colDetails", typeof(String)); ... conn.Open(); using (SqlDataReader r = cmd.ExecuteReader()) { while (r.Read()) { entries.Rows.Add(result.GetInt32(0), result.GetInt32(1), result.GetString(2)); } } return entries; }

    Read the article

  • NullReferenceException in EntityFramework, how come?

    - by Mickel
    Take a look at this query: var user = GetUser(userId); var sessionInvites = ctx.SessionInvites .Include("InvitingUser") .Include("InvitedUser") .Where(e => e.InvitedUser.UserId == user.UserId) .ToList(); var invites = sessionInvites; // Commenting out the two lines below, and it works as expected. foreach (var invite in sessionInvites) ctx.DeleteObject(invite); ctx.SaveChanges(); return invites; Now, everything here executes without any errors. The invites that exists for the user are being deleted and the invites are being returned with success. However, when I then try to navigate to either InvitingUser or InvitedUser on any of the returned invites, I get NullReferenceException. All other properties of the SessionIvites returned, works fine. How come? [EDIT] Now the weird thing is, if I comment out the lines with delete it works as expected. (Except that the entities will not get deleted :S)

    Read the article

  • Logging class using delegates (NullReferenceException)

    - by Leroy Jenkins
    I have created a small application but I would now like to incorporate some type of logging that can be viewed via listbox. The source of the data can be sent from any number of places. I have created a new logging class that will pass in a delegate. I think Im close to a solution but Im receiving a NullReferenceException and I don’t know the proper solution. Here is an example of what Im trying to do: Class1 where the inbound streaming data is received. class myClass { OtherClass otherClass = new OtherClass(); otherClass.SendSomeText(myString); } Logging Class class OtherClass { public delegate void TextToBox(string s); TextToBox textToBox; Public OtherClass() { } public OtherClass(TextToBox ttb) { textToBox = ttb; } public void SendSomeText(string foo) { textToBox(foo); } } The Form public partial class MainForm : Form { OtherClass otherClass; public MainForm() { InitializeComponent(); otherClass = new OtherClass(this.TextToBox); } public void TextToBox(string pString) { listBox1.Items.Add(pString); } } Whenever I receive data in myClass, its throwing an error. Any help you could give would be appreciated.

    Read the article

  • Whose fault is a NullReferenceException?

    - by stefan.at.wpf
    I'm currently working on a class which exposes an internal List through a property. The List shall and can be modified. The problem is, entries in the internal list could be set to null from outside the class. My code actually looks like this: class ClassWithList { List<object> _list = new List<object>(); // get accessor, which however returns the reference to the list, // therefore the list can be modified (this is intended) public List<object> Data { get { return _list; } } private void doSomeWorkWithTheList() { foreach(object obj in _list) // do some work with the objects in the list without checking for null. } } So now in the doSomeWorkWithTheList() I could always check whether the current list entry is null or I could just asume that the person using this class doesn't have the great idea to set entries to null. So finally the questions end up in: Whose fault is a NullReferenceException in this case? Is it the fault of the class developer not checking everything for null (which would make code generally - not only in this class - more complex) or is it the fault of the user of this class, as setting a List entry to null doesn't really make sense? I'd tend to generally not check values for null except in some really special cases. Is this a bad style or de facto standard / standard in praxis? I know there's probably no ultimate answer for this, I'm just missing enough experience for such thing and therefore wondering what other developers think about such cases and want to hear what's done in reality about checking null (or not).

    Read the article

  • NullReferenceException when calling InsertOnSubmit in Linq to Sql.

    - by Charlie
    I'm trying to insert a new object into my database using LINQ to SQL but get a NullReferenceException when I call InsertOnSubmit() in the code snippet below. I'm passing in a derived class called FileUploadAudit, and all properties on the object are set. public void Save(Audit audit) { try { using (ULNDataClassesDataContext dataContext = this.Connection.GetContext()) { if (audit.AuditID > 0) { throw new RepositoryException(RepositoryExceptionCode.EntityAlreadyExists, string.Format("An audit entry with ID {0} already exists and cannot be updated.", audit.AuditID)); } dataContext.Audits.InsertOnSubmit(audit); dataContext.SubmitChanges(); } } catch (Exception ex) { if (ObjectFactory.GetInstance<IExceptionHandler>().HandleException(ex)) { throw; } } } Here's the stack trace: at System.Data.Linq.Table`1.InsertOnSubmit(TEntity entity) at XXXX.XXXX.Repository.AuditRepository.Save(Audit audit) C:\XXXX\AuditRepository.cs:line 25" I've added to the Audit class like this: public partial class Audit { public Audit(string message, ULNComponent component) : this() { this.Message = message; this.DateTimeRecorded = DateTime.Now; this.SetComponent(component); this.ServerName = Environment.MachineName; } public bool IsError { get; set; } public void SetComponent(ULNComponent component) { this.Component = Enum.GetName(typeof(ULNComponent), component); } } And the derived FileUploadAudit looks like this: public class FileUploadAudit : Audit { public FileUploadAudit(string message, ULNComponent component, Guid fileGuid, string originalFilename, string physicalFilename, HttpPostedFileBase postedFile) : base(message, component) { this.FileGuid = fileGuid; this.OriginalFilename = originalFilename; this.PhysicalFileName = physicalFilename; this.PostedFile = postedFile; this.ValidationErrors = new List<string>(); } public Guid FileGuid { get; set; } public string OriginalFilename { get; set; } public string PhysicalFileName { get; set; } public HttpPostedFileBase PostedFile { get; set; } public IList<string> ValidationErrors { get; set; } } Any ideas what the problem is? The closest question I could find to mine is here but my partial Audit class is calling the parameterless constructor in the generated code, and I still get the problem. UPDATE: This problem only occurs when I pass in the derived FileUploadAudit class, the Audit class works fine. The Audit class is generated as a linq to sql class and there are no Properties mapped to database fields in the derived class.

    Read the article

  • NullReferenceException makes me want to shoot myself

    - by rockinthesixstring
    Ok, so once upon a time, my code worked. Since then I did some refactoring (basic stuff so I thought) but now I'm getting a null reference exception, and I can't bloody well figure out why. Here's where it starts. note, this is the logout method, but all of my ActivityLogs sections are throwing this error Function LogOut(ByVal go As String) As ActionResult ActivityLogService.AddActivity(AuthenticationHelper.RetrieveAuthUser.ID, _ IActivityLogService.LogType.UserLogout, _ HttpContext.Request.UserHostAddress) ActivityLogService.SubmitChanges() ''# more stuff happens after this End Function The service is pretty straight forward (notice the ERROR THROWN HERE) Public Sub AddActivity(ByVal userid As Integer, ByVal activity As Integer, ByVal ip As String) Implements IActivityLogService.AddActivity Dim _activity As ActivityLog = New ActivityLog With {.Activity = activity, .UserID = userid, .UserIP = ip.IPAddressToNumber, .ActivityDate = DateTime.UtcNow} ActivityLogRepository.Create(_activity) ''#ERROR THROWN HERE End Sub And the Interface that the Service uses looks like this Public Interface IActivityLogService Sub AddActivity(ByVal userid As Integer, ByVal activity As Integer, ByVal ip As String) Function GetUsersLastActivity(ByVal UserID As Integer) As ActivityLog Sub SubmitChanges() ''' <summary> ''' The type of activity done by the user ''' </summary> ''' <remarks>Each int refers to an activity. ''' There can be no duplicates or modifications ''' after this application goes live</remarks> Enum LogType As Integer ''' <summary> ''' A new session started ''' </summary> SessionStarted = 1 ''' <summary> ''' A new user is Added/Created ''' </summary> UserAdded = 2 ''' <summary> ''' User has updated their profile ''' </summary> UserUpdated = 3 ''' <summary> ''' User has logged into they system ''' </summary> UserLogin = 4 ''' <summary> ''' User has logged out of the system ''' </summary> UserLogout = 5 ''' <summary> ''' A new event has been added ''' </summary> EventAdded = 6 ''' <summary> ''' An event has been updated ''' </summary> EventUpdated = 7 ''' <summary> ''' An event has been deleted ''' </summary> EventDeleted = 8 ''' <summary> ''' An event has received a Up/Down vote ''' </summary> EventVoted = 9 ''' <summary> ''' An event has been closed ''' </summary> EventCloseVoted = 10 ''' <summary> ''' A comment has been added to an event ''' </summary> CommentAdded = 11 ''' <summary> ''' A comment has been updated ''' </summary> CommentUpdated = 12 ''' <summary> ''' A comment has been deleted ''' </summary> CommentDeleted = 13 ''' <summary> ''' An event or comment has been reported as spam ''' </summary> SpamReported = 14 End Enum End Interface And the repository is equally straight forward Public Sub Create(ByVal activity As ActivityLog) Implements IActivityLogRepository.Create dc.ActivityLogs.InsertOnSubmit(activity) End Sub The stack trace is as follows [NullReferenceException: Object reference not set to an instance of an object.] MyApp.Core.Domain.ActivityLogService.AddActivity(Int32 userid, Int32 activity, String ip) in E:\Projects\MyApp\MyApp.Core\Domain\Services\ActivityLogService.vb:49 MyApp.Core.Controllers.UsersController.Authenticate(String go) in E:\Projects\MyApp\MyApp.Core\Controllers\UsersController.vb:258 lambda_method(Closure , ControllerBase , Object[] ) +163 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +51 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +409 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +52 System.Web.Mvc.<c_DisplayClass15.b_12() +127 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func1 continuation) +436 System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +61 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor, IDictionary2 parameters) +305 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830 System.Web.Mvc.Controller.ExecuteCore() +136 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +232 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39 System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +68 System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44 System.Web.Mvc.Async.<>c__DisplayClass81.b__7(IAsyncResult ) +42 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40 System.Web.Mvc.<c_DisplayClasse.b_d() +61 System.Web.Mvc.SecurityUtil.b_0(Action f) +31 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +56 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +110 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +690 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +194 here's an image of the error when attached to the debugger. And here's an image of the DB schema in question Can anyone shed some light on what I might be missing here?

    Read the article

  • Properly handling possible System.NullReferenceException in lambda expressions

    - by Travis Johnson
    Here's the query in question return _projectDetail.ExpenditureDetails .Where(detail => detail.ProgramFund == _programFund && detail.Expenditure.User == _creditCardHolder) .Sum(detail => detail.ExpenditureAmounts.FirstOrDefault( amount => amount.isCurrent && !amount.requiresAudit) .CommittedMonthlyRecord.ProjectedEac); Table Structure ProjectDetails (1 to Many) ExpenditureDetails ExpenditureDetails (1 to Many) ExpenditureAmounts ExpenditureAmounts (1 to 1) CommittedMonthlyRecords ProjectedEac is a decimal field on the CommittedMonthlyRecords. The problem I discovered in a Unit test (albeit an unlikely event), that the following line could be null: detail.ExpenditureAmounts.FirstOrDefault( amount => amount.isCurrent && !amount.requiresAudit) My original query was a nested loop, in where I would be making multiple trips to the database, something I don't want to repeat. I've looked in to what seemed like some similar questions here, but the solution didn't seem to fit. Any ideas?

    Read the article

  • Nullreferenceexception when adding a GData.Extensions.Reminder to Reminders

    - by user283182
    Hello again, I think the title says it all. I'm using Reminder fifteenMinReminder = new Reminder(); fifteenMinReminder.Minutes = 15; fifteenMinReminder.Method = Reminder.ReminderMethod.email; entry.Reminders.Add(fifteenMinReminder); on a brand new entry (where Reminder and Reminders are Nothing), but I cannot add a reminder using the above code (taken straight from the Google Docs), or set the entry.Reminder to fifteenMinReminder directly either. What am I doing wrong? I've had no trouble .adding When and Where's to the entry, but the Reminder doesn't want to follow the same pattern. Any ideas?

    Read the article

  • Problem with Unit testing of ASP.NET project (NullReferenceException when running the test)

    - by Alex
    Hi, I'm trying to create a bunch of MS visual studio unit tests for my n-tiered web app but for some reason I can't run those tests and I get the following error - "Object reference not set to an instance of an object" What I'm trying to do is testing of my data access layer where I use LINQ data context class to execute a certain function and return a result,however during the debugging process I found out that all the tests fail as soon as they get to the LINQ data context class and it has something to do with the connection string but I cant figure out what is the problem. The debugging of tests fails here(the second line): public EICDataClassesDataContext() : base(global::System.Configuration.ConfigurationManager.ConnectionStrings["EICDatabaseConnectionString"].ConnectionString, mappingSource) { OnCreated(); } And my test is as follows: TestMethod()] public void OnGetCustomerIDTest() { FrontLineStaffDataAccess target = new FrontLineStaffDataAccess(); // TODO: Initialize to an appropriate value string regNo = "jonh"; // TODO: Initialize to an appropriate value int expected = 10; // TODO: Initialize to an appropriate value int actual; actual = target.OnGetCustomerID(regNo); Assert.AreEqual(expected, actual); } The method which I call from DAL is: public int OnGetCustomerID(string regNo) { using (LINQDataAccess.EICDataClassesDataContext dataContext = new LINQDataAccess.EICDataClassesDataContext()) { IEnumerable<LINQDataAccess.GetCustomerIDResult> sProcCustomerIDResult = dataContext.GetCustomerID(regNo); int customerID = sProcCustomerIDResult.First().CustomerID; return customerID; } } So basically everything fails after it reaches the 1st line of DA layer method and when it tries to instantiate the LINQ data access class... I've spent around 10 hours trying to troubleshoot the problem but no result...I would really appreciate any help! UPDATE: Finally I've fixed this!!!!:) I dont know why but for some reasons in the app.config file the connection to my database was as follows: AttachDbFilename=|DataDirectory|\EICDatabase.MDF So what I did is I just changed the path and instead of |DataDirectory| I put the actual path where my MDF file sits,i.e C:\Users\1\Documents\Visual Studio 2008\Projects\EICWebSystem\EICWebSystem\App_Data\EICDatabase.mdf After I had done that it worked out!But still it's a bit not clear what was the problem...probably incorrect path to the database?My web.config of ASP.NET project contains the |DataDirectory|\EICDatabase.MDF path though..

    Read the article

  • ASP.NET MVC NullReferenceException when inheriting from a Base Controller

    - by rockinthesixstring
    I've got a base controller that I inherit all of my Controllers from. It's job is to basically set caching and error handling as well as check for mobile browsers. My UI works fine, but my Unit Tests are failing. Imports System.Web.Mvc <HandleError()> _ <CompressFilter()> _ <OutputCache(Duration:=30, VaryByParam:="id")> _ Public Class BaseController : Inherits System.Web.Mvc.Controller Protected Overrides Function View(ByVal viewName As String, ByVal masterName As String, ByVal model As Object) As System.Web.Mvc.ViewResult Dim ismobile As Nullable(Of Boolean) = Request.Browser.IsMobileDevice If ismobile Then Return MyBase.View(viewName, "Mobile", model) Else Return MyBase.View(viewName, "Site", model) End If End Function End Class The error I'm getting in my Unit test is on Dim ismobile As Nullable(Of Boolean) = Request.Browser.IsMobileDevice saying Object Reference Not Set To An Instance Of An Object.

    Read the article

  • Workaround for datadude deployment bug - NullReferenceException

    - by jamiet
    I have come across a bug in Visual Studio 2010 Database Projects (aka datadude aka DPro aka Visual Studio Database Development Tools aka Visual Studio Team Edition for Database Professionals aka Juneau aka SQL Server Data Tools) that other people may encounter so, for the purposes of googling, I'm writing this blog post about it. Through my own googling I discovered that a Connect bug had already been raised about it (VS2010 Database project deploy - “SqlDeployTask” task failed unexpectedly, NullReferenceException), and coincidentally enough it was raised by my former colleague Tom Hunter (whom I have mentioned here before as the superhuman Tom Hunter) although it has not (at this time) received a reply from Microsoft. Tom provided a repro, namely that this syntactically valid function definition: CREATE FUNCTION [dbo].[Function1]()RETURNS TABLEASRETURN (    WITH cte AS (    SELECT 1 AS [c1]    FROM [$(Database3)].[dbo].[Table1]   )   SELECT 1 AS [c1]   FROM cte) would produce this nasty unhelpful error upon deployment: C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\TeamData\Microsoft.Data.Schema.TSqlTasks.targets(120,5): Error MSB4018: The "SqlDeployTask" task failed unexpectedly.System.NullReferenceException: Object reference not set to an instance of an object.   at Microsoft.Data.Schema.Sql.SchemaModel.SqlModelComparerBase.VariableSubstitution(SqlScriptProperty propertyValue, IDictionary`2 variables, Boolean& isChanged)   at Microsoft.Data.Schema.Sql.SchemaModel.SqlModelComparerBase.ArePropertiesEqual(IModelElement source, IModelElement target, ModelPropertyClass propertyClass, ModelComparerConfiguration configuration)   at Microsoft.Data.Schema.SchemaModel.ModelComparer.CompareProperties(IModelElement sourceElement, IModelElement targetElement, ModelComparerConfiguration configuration, ModelComparisonChangeDefinition changes)   at Microsoft.Data.Schema.SchemaModel.ModelComparer.CompareElementsWithoutCompareName(IModelElement sourceElement, IModelElement targetElement, ModelComparerConfiguration configuration, Boolean parentExplicitlyIncluded, Boolean compareElementOnly, ModelComparisonResult result, ModelComparisonChangeDefinition changes)   at Microsoft.Data.Schema.SchemaModel.ModelComparer.CompareElementsWithSameType(IModelElement sourceElement, IModelElement targetElement, ModelComparerConfiguration configuration, ModelComparisonResult result, Boolean ignoreComparingName, Boolean parentExplicitlyIncluded, Boolean compareElementOnly, Boolean compareFromRootElement, ModelComparisonChangeDefinition& changes)   at Microsoft.Data.Schema.SchemaModel.ModelComparer.CompareChildren(IModelElement sourceElement, IModelElement targetElement, ModelComparerConfiguration configuration, Boolean parentExplicitlyIncluded, Boolean compareParentElementOnly, ModelComparisonResult result, ModelComparisonChangeDefinition changes, Boolean isComposing)   at Microsoft.Data.Schema.SchemaModel.ModelComparer.CompareElementsWithoutCompareName(IModelElement sourceElement, IModelElement targetElement, ModelComparerConfiguration configuration, Boolean parentExplicitlyIncluded, Boolean compareElementOnly, ModelComparisonResult result, ModelComparisonChangeDefinition changes)   at Microsoft.Data.Schema.SchemaModel.ModelComparer.CompareElementsWithSameType(IModelElement sourceElement, IModelElement targetElement, ModelComparerConfiguration configuration, ModelComparisonResult result, Boolean ignoreComparingName, Boolean parentExplicitlyIncluded, Boolean compareElementOnly, Boolean compareFromRootElement, ModelComparisonChangeDefinition& changes)   at Microsoft.Data.Schema.SchemaModel.ModelComparer.CompareChildren(IModelElement sourceElement, IModelElement targetElement, ModelComparerConfiguration configuration, Boolean parentExplicitlyIncluded, Boolean compareParentElementOnly, ModelComparisonResult result, ModelComparisonChangeDefinition changes, Boolean isComposing)   at Microsoft.Data.Schema.SchemaModel.ModelComparer.CompareElementsWithoutCompareName(IModelElement sourceElement, IModelElement targetElement, ModelComparerConfiguration configuration, Boolean parentExplicitlyIncluded, Boolean compareElementOnly, ModelComparisonResult result, ModelComparisonChangeDefinition changes)   at Microsoft.Data.Schema.SchemaModel.ModelComparer.CompareElementsWithSameType(IModelElement sourceElement, IModelElement targetElement, ModelComparerConfiguration configuration, ModelComparisonResult result, Boolean ignoreComparingName, Boolean parentExplicitlyIncluded, Boolean compareElementOnly, Boolean compareFromRootElement, ModelComparisonChangeDefinition& changes)   at Microsoft.Data.Schema.SchemaModel.ModelComparer.CompareAllElementsForOneType(ModelElementClass type, ModelComparerConfiguration configuration, ModelComparisonResult result, Boolean compareOrphanedElements)   at Microsoft.Data.Schema.SchemaModel.ModelComparer.CompareStore(ModelStore source, ModelStore target, ModelComparerConfiguration configuration)   at Microsoft.Data.Schema.Build.SchemaDeployment.CompareModels()   at Microsoft.Data.Schema.Build.SchemaDeployment.PrepareBuildPlan()   at Microsoft.Data.Schema.Build.SchemaDeployment.Execute(Boolean executeDeployment)   at Microsoft.Data.Schema.Build.SchemaDeployment.Execute()   at Microsoft.Data.Schema.Tasks.DBDeployTask.Execute()   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()   at Microsoft.Build.BackEnd.TaskBuilder.ExecuteInstantiatedTask(ITaskExecutionHost taskExecutionHost, TaskLoggingContext taskLoggingContext, TaskHost taskHost, ItemBucket bucket, TaskExecutionMode howToExecuteTask, Boolean& taskResult)   Done executing task "SqlDeployTask" -- FAILED.  Done building target "DspDeploy" in project "Lloyds.UKTax.DB.UKtax.dbproj" -- FAILED. Done executing task "CallTarget" -- FAILED.Done building target "DBDeploy" in project It turns out there are a certain set of circumstances that need to be met for this error to occur: The object being deployed is an inline function  (may also exist for multistatement and scalar functions - I haven't tested that) That object includes SQLCMD variable references The object has already been deployed successfully Just to reiterate that last bullet point, the error does not occur when you deploy the function for the first time, only on the subsequent deployment.   Luckily I have a direct line into a guy on the development team so I fired off an email on Friday evening and today (Monday) I received a reply back telling me that there is a simple fix, one simply has to remove the parentheses that wrap the SQL statement. So, in the case of Tom's repro, the function definition simpy has to be changed to: CREATE FUNCTION [dbo].[Function1]()RETURNS TABLEASRETURN --(    WITH cte AS (    SELECT 1 AS [c1]    FROM [$(Database3)].[dbo].[Table1]   )   SELECT 1 AS [c1]   FROM cte--) I have commented out the offending parentheses rather than removing them just to emphasize the point. Thereafter the function will deploy fine. I tested this out on my own project this morning and can confirm that this fix does indeed work.   I have been told that the bug CAN be reproduced in the Release Candidate (RC) 0 build of SQL Server Data Tools in SQL Server 2010 so am hoping that a fix makes it in for the Release-To-Manufacturing (RTM) build. Hope this helps @jamiet

    Read the article

  • NullReferenceException when accessing variables in a 2D array in Unity

    - by Syed
    I have made a class including variables in Monodevelop which is: public class GridInfo : MonoBehaviour { public float initPosX; public float initPosY; public bool inUse; public int f; public int g; public int h; public GridInfo parent; public int y,x; } Now I am using its class variable in another class, Map.cs which is: public class Map : MonoBehaviour { public static GridInfo[,] Tile = new GridInfo[17, 23]; void Start() { Tile[0,0].initPosX = initPosX; //Line 49 } } I am not getting any error on runtime, but when I play in unity it is giving me error NullReferenceException: Object reference not set to an instance of an object Map.Start () (at Assets/Scripts/Map.cs:49) I am not inserting this script in any gameobject, as Map.cs will make a GridInfo type array, I have also tried using variables using GetComponent, where is the problem ?

    Read the article

  • Fix: SqlDeploy Task Fails with NullReferenceException at ExtractPassword

    Still working on getting a TeamCity build working (see my last post).  Latest exception is: C:\Program Files\MSBuild\Microsoft\VisualStudio\v9.0\TeamData\Microsoft.Data.Schema.SqlTasks.targets(120, 5): error MSB4018: The "SqlDeployTask" task failed unexpectedly. System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.Data.Schema.Common.ConnectionStringPersistence.ExtractPassword(String partialConnection, String dbProvider) at Microsoft.Data.Schema.Common.ConnectionStringPersistence.RetrieveFullConnection(String partialConnection, String provider, Boolean presentUI, String password) at Microsoft.Data.Schema.Sql.Build.SqlDeployment.ConfigureConnectionString(String connectionString, String databaseName) at Microsoft.Data.Schema.Sql.Build.SqlDeployment.OnBuildConnectionString(String partialConnectionString, String databaseName) at Microsoft.Data.Schema.Build.Deployment.FinishInitialize(String targetConnectionString) at Microsoft.Data.Schema.Build.Deployment.Initialize(FileInfo sourceDbSchemaFile, ErrorManager errors, String targetConnectionString) at Microsoft.Data.Schema.Build.DeploymentConstructor.ConstructServiceImplementation() at Microsoft.Data.Schema.Extensibility.ServiceConstructor'1.ConstructService() at Microsoft.Data.Schema.Tasks.DBDeployTask.Execute() at Microsoft.Build.BuildEngine.TaskEngine.ExecuteInstantiatedTask(EngineProxy engineProxy, ItemBucket bucket, TaskExecutionMode howToExecuteTask, ITask task, Boolean& taskResult)   This time searching yielded some good stuff, including this thread that talks about how to resolve this via permissions.  The short answer is that the account that your build server runs under needs to have the necessary permissions in SQL Server.  Youll need to create a Login and then ensure at least the minimum rights are configured as described here: Required Permissions in Database Edition Alternately, you can just make your buildserver account an admin on the database (which is probably running on the same machine anyway) and at that point it should be able to do whatever it needs to. If youre certain the account has the necessary permissions, but youre still getting the error, the problem may be that the account has never logged into the build server.  In this case, there wont be any entry in the HKCU hive in the registry, which the system is checking for permissions (see this thread).  The solution in this case is quite simple: log into the machine (once is enough) with the build server account.  Then, open Visual Studio (thanks Brendan for the answer in this thread). Summary Make sure the build service account has the necessary database permissions Make sure the account has logged into the server so it has the necessary registry hive info Make sure the account has run Visual Studio at least once so its settings are established In my case I went through all 3 of these steps before I resolved the problem. Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Why is a NullReferenceException thrown when a ToolStrip button is clicked twice with code in the `Click` event handler?

    - by Patrick
    I created a clean WindowsFormsApplication solution, added a ToolStrip to the main form, and placed one button on it. I've added also an OpenFileDialog, so that the Click event of the ToolStripButton looks like the following: private void toolStripButton1_Click(object sender, EventArgs e) { openFileDialog1.ShowDialog(); } I didn't change any other properties or events. The funny thing is that when I double-click the ToolStripButton (the second click must be quite fast, before the dialog opens), then cancel both dialogs (or choose a file, it doesn't really matter) and then click in the client area of main form, a NullReferenceException crashes the application (error details attached at the end of the post). Please note that the Click event is implemented while DoubleClick is not. What's even more strange that when the OpenFileDialog is replaced by any user-implemented form, the ToolStripButton blocks from being clicked twice. I'm using VS2008 with .NET3.5. I didn't change many options in VS (only fontsize, workspace folder and line numbering). Does anyone know how to solve this? It is 100% replicable on my machine, is it on others too? One solution that I can think of is disabling the button before calling OpenFileDialog.ShowDialog() and then enabling the button back (but it's not nice). Any other ideas? And now the promised error details: System.NullReferenceException was unhandled Message="Object reference not set to an instance of an object." Source="System.Windows.Forms" StackTrace: at System.Windows.Forms.NativeWindow.WindowClass.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.PeekMessage(MSG& msg, HandleRef hwnd, Int32 msgMin, Int32 msgMax, Int32 remove) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at WindowsFormsApplication1.Program.Main() w C:\Users\Marchewek\Desktop\Workspaces\VisualStudio\WindowsFormsApplication1\Program.cs:line 20 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException:

    Read the article

  • Why does this extension method throw a NullReferenceException in VB.NET?

    - by Dan
    From previous experience I had been under the impression that it's perfectly legal (though perhaps not advisable) to call extension methods on a null instance. So in C#, this code compiles and runs: // code in static class static bool IsNull(this object obj) { return obj == null; } // code elsewhere object x = null; bool exists = !x.IsNull(); However, I was just putting together a little suite of example code for the other members of my development team (we just upgraded to .NET 3.5 and I've been assigned the task of getting the team up to speed on some of the new features available to us), and I wrote what I thought was the VB.NET equivalent of the above code, only to discover that it actually throws a NullReferenceException. The code I wrote was this: ' code in module ' <Extension()> _ Function IsNull(ByVal obj As Object) As Boolean Return obj Is Nothing End Function ' code elsewhere ' Dim exampleObject As Object = Nothing Dim exists As Boolean = Not exampleObject.IsNull() The debugger stops right there, as if I'd called an instance method. Am I doing something wrong (e.g., is there some subtle difference in the way I defined the extension method between C# and VB.NET)? Is it actually not legal to call an extension method on a null instance in VB.NET, though it's legal in C#? (I would have thought this was a .NET thing as opposed to a language-specific thing, but perhaps I was wrong.) Can anybody explain this one to me?

    Read the article

  • AD FS 2.0: Troubleshooting Event 364 and ThrowExceptionForHRInternal / NullReferenceException

    - by Shawn Cicoria
    Ran into a situation today where after AD FS federation server was installed, configured and up & running, “all of a sudden” it stopped working. Turned out that another installer that affected the default web site, also seemingly affected the AppPools associated to all Applications under the Default Web site. By changing the “Enable 32-bit Applications” either through IIS admin or via command line appcmd set apppool /apppool.name:MyAppPool /enable32BitAppOnWin64:false Back to normal…

    Read the article

  • Beginner C# image loading woes - NullReferenceException

    - by Seth Taddiken
    I keep getting a "NullReferenceExeption was unhandled" with "Object reference not set to an instance of an object." written under it. I have all of the images (png) correct with names and added to references. protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); backGround = Content.Load<Texture2D>("Cracked"); player1.playerBlock = Content.Load<Texture2D>("square"); player2.playerBlock = Content.Load<Texture2D>("square2"); }

    Read the article

  • Linq to SQL NullReferenceException's: A random needle in a haystack!

    - by Shane
    I'm getting NullReferenceExeceptions at seemly random times in my application and can't track down what could be causing the error. I'll do my best to describe the scenario and setup. Any and all suggestions greatly appreciated! C# .net 3.5 Forms Application, but I use the WebFormRouting library built by Phil Haack (http://haacked.com/archive/2008/03/11/using-routing-with-webforms.aspx) to leverage the Routing libraries of .net (usually used in conjunction with MVC) - intead of using url rewriting for my urls. My database has 60 tables. All Normalized. It's just a massive application. (SQL server 2008) All queries are built with Linq to SQL in code (no SP's). Each time a new instance of my data context is created. I use only one data context with all relationships defined in 4 relationship diagrams in SQL Server. the data context gets created a lot. I let the closing of the data context be handled automatically. I've heard arguments both sides about whether you should leave to be closed automatically or do it yourself. In this case I do it myself. It doesnt seem to matter if I'm creating a lot of instances of the data context or just one. For example, I've got a vote-up button. with the following code, and it errors probably 1 in 10-20 times. protected void VoteUpLinkButton_Click(object sender, EventArgs e) { DatabaseDataContext db = new DatabaseDataContext(); StoryVote storyVote = new StoryVote(); storyVote.StoryId = storyId; storyVote.UserId = Utility.GetUserId(Context); storyVote.IPAddress = Utility.GetUserIPAddress(); storyVote.CreatedDate = DateTime.Now; storyVote.IsDeleted = false; db.StoryVotes.InsertOnSubmit(storyVote); db.SubmitChanges(); // If this story is not yet published, check to see if we should publish it. Make sure that // it is already approved. if (story.PublishedDate == null && story.ApprovedDate != null) { Utility.MakeUpcommingNewsPopular(storyId); } // Refresh our page. Response.Redirect("/news/" + category.UniqueName + "/" + RouteData.Values["year"].ToString() + "/" + RouteData.Values["month"].ToString() + "/" + RouteData.Values["day"].ToString() + "/" + RouteData.Values["uniquename"].ToString()); } The last thing I tried was the "Auto Close" flag setting on SQL Server. This was set to true and I changed to false. Doesnt seem to have done the trick although has had a good overall effect. Here's a detailed that wasnt caught. I also get slighly different errors when caught by my try/catch's. System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. --- System.NullReferenceException: Object reference not set to an instance of an object. at System.Web.Util.StringUtil.GetStringHashCode(String s) at System.Web.UI.ClientScriptManager.EnsureEventValidationFieldLoaded() at System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) at System.Web.UI.WebControls.TextBox.LoadPostData(String postDataKey, NameValueCollection postCollection) at System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) --- End of inner exception stack trace --- at System.Web.UI.Page.HandleError(Exception e) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.forms_news_detail_aspx.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) HELP!!!

    Read the article

  • Ninject giving NullReferenceException

    - by Iceman
    I'm using asp.net MVC 2 and Ninject 2. The setup is very simple. Controller calls service that calls repository. In my controller I use inject to instantiate the service classes with no problem. But the service classes don't instantiate the repositories, giving me NullReferenceException. public class BaseController : Controller { [Inject] public IRoundService roundService { get; set; } } This works. But then this does not... public class BaseService { [Inject] public IRoundRepository roundRepository { get; set; } } Giving a NullReferenceException, when I try to use the roundRepository in my RoundService class. IList<Round> rounds = roundRepository.GetRounds( ); Module classes... public class ServiceModule : NinjectModule { public override void Load( ) { Bind( ).To( ).InRequestScope( ); } } public class RepositoryModule : NinjectModule { public override void Load( ) { Bind<IRoundRepository>( ).To<RoundRepository>( ).InRequestScope( ); } } In global.axax.cs protected override IKernel CreateKernel( ) { return new StandardKernel( new ServiceModule( ), new RepositoryModule( ) ); }

    Read the article

  • NHibernate (3.1.0.4000) NullReferenceException using Query<> and NHibernate Facility

    - by TigerShark
    I have a problem with NHibernate, I can't seem to find any solution for. In my project I have a simple entity (Batch), but whenever I try and run the following test, I get an exception. I've triede a couple of different ways to perform a similar query, but almost identical exception for all (it differs in which LINQ method being executed). The first test: [Test] public void QueryLatestBatch() { using (var session = SessionManager.OpenSession()) { var batch = session.Query<Batch>() .FirstOrDefault(); Assert.That(batch, Is.Not.Null); } } The exception: System.NullReferenceException : Object reference not set to an instance of an object. at NHibernate.Linq.NhQueryProvider.PrepareQuery(Expression expression, ref IQuery query, ref NhLinqExpression nhQuery) at NHibernate.Linq.NhQueryProvider.Execute(Expression expression) at System.Linq.Queryable.FirstOrDefault(IQueryable`1 source) The second test: [Test] public void QueryLatestBatch2() { using (var session = SessionManager.OpenSession()) { var batch = session.Query<Batch>() .OrderBy(x => x.Executed) .Take(1) .SingleOrDefault(); Assert.That(batch, Is.Not.Null); } } The exception: System.NullReferenceException : Object reference not set to an instance of an object. at NHibernate.Linq.NhQueryProvider.PrepareQuery(Expression expression, ref IQuery query, ref NhLinqExpression nhQuery) at NHibernate.Linq.NhQueryProvider.Execute(Expression expression) at System.Linq.Queryable.SingleOrDefault(IQueryable`1 source) However, this one is passing (using QueryOver<): [Test] public void QueryOverLatestBatch() { using (var session = SessionManager.OpenSession()) { var batch = session.QueryOver<Batch>() .OrderBy(x => x.Executed).Asc .Take(1) .SingleOrDefault(); Assert.That(batch, Is.Not.Null); Assert.That(batch.Executed, Is.LessThan(DateTime.Now)); } } Using the QueryOver< API is not bad at all, but I'm just kind of baffled that the Query< API isn't working, which is kind of sad, since the First() operation is very concise, and our developers really enjoy LINQ. I really hope there is a solution to this, as it seems strange if these methods are failing such a simple test. EDIT I'm using Oracle 11g, my mappings are done with FluentNHibernate registered through Castle Windsor with the NHibernate Facility. As I wrote, the odd thing is that the query works perfectly with the QueryOver< API, but not through LINQ.

    Read the article

1 2 3 4 5 6 7 8 9 10 11  | Next Page >