Search Results

Search found 21 results on 1 pages for 'nullreference'.

Page 1/1 | 1 

  • Change in behaviour & generation of nullreference exception

    - by peril brain
    I made this program 2hr ago and it ran quit well when i confronted this to presaved .xls file. But when i closed that and started new instance,it started generating null refrence exception why??plz explain. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; using Microsoft.Office.Interop; using Excel = Microsoft.Office.Interop.Excel; namespace svchost { class MainClass { Excel.Application oExcelApp; static void Main(string[] args) { MainClass mc = new MainClass(); while (true) { if (mc.chec()) { Console.WriteLine("RUNNING"); Thread.Sleep(4000); } else { Console.WriteLine("NOT RUNNING"); Thread.Sleep(8000); } } } public bool chec() { try { oExcelApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); Excel.Workbook xlwkbook = (Excel.Workbook)oExcelApp.ActiveWorkbook; //****PROBLEM FROM HERE********* Console.WriteLine(xlwkbook.Name + "\n"); ke kw = new ke(ref oExcelApp,ref xlwkbook); Console.WriteLine(xlwkbook.Author); xlwkbook = null; } catch (Exception ec) { oExcelApp = null; System.GC.Collect(); Console.WriteLine(ec); return false; } oExcelApp = null; System.GC.Collect(); return true; } } class ke { public ke(ref Excel.Application a1, ref Excel.Workbook b1) { Excel.Worksheet ws = (Excel.Worksheet)a1.ActiveSheet; Console.WriteLine(a1.ActiveWorkbook.Name + "\n" + ws.Name); Excel.Range rn; rn = ws.Cells.Find("657/07", Type.Missing, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false, Type.Missing, Type.Missing); Console.WriteLine(rn.Text); } } }

    Read the article

  • odd nullreference error at foreach when rendering view

    - by giddy
    This error is so weird I Just can't really figure out what is really wrong! In UserController I have public virtual ActionResult Index() { var usersmdl = from u in RepositoryFactory.GetUserRepo().GetAll() select new UserViewModel { ID = u.ID, UserName = u.Username, UserGroupName = u.UserGroupMain.GroupName, BranchName = u.Branch.BranchName, Password = u.Password, Ace = u.ACE, CIF = u.CIF, PF = u.PF }; if (usersmdl != null) { return View(usersmdl.AsEnumerable()); } return View(); } My view is of type @model IEnumerable<UserViewModel> on the top. This is what happens: Where and what exactly IS null!? I create the users from a fake repository with moq. I also wrote unit tests, which pass, to ensure the right amount of mocked users are returned. Maybe someone can point me in the right direction here? Top of the stack trace is : at lambda_method(Closure , User ) at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext() at ASP.Index_cshtml.Execute() Is it something to do with linq here? Tell me If I should include the full stack trace.

    Read the article

  • Regarding Visual C# MenuItem: Where does the NullReference come from?

    - by Thomas
    Hi All. I have a problem creating MenuItems for a TreeView dynamically: here is the (simplified)code i'm using. public class CTM : TreeNode, IComparable, IComparable<CTM> { public CTM(CTMProvider provider) { this.provider = provider; this.manager = provider.manager; this.IEEEAddress = provider.IEEEAddress; this.endpoint = provider.state._conn.RemoteEndPoint; this.Text = String.Format("CTM: {0} {0}", IEEEAddress, ((System.Net.IPEndPoint)endpoint).ToString()); try { MenuItem meni = System.EventHandler(this.provider.Disconnect)); this.ContextMenu.MenuItems.Add(meni); } catch { Trace.TraceError("Could not create menu item!"); } } } This code always triggers the catch clause with a NullReferenceException. Any Ideas?

    Read the article

  • Is there any danger in disabling windows firewall on a azure worker role?

    - by NullReference
    I'm trying to troubleshoot a bug on our Azure worker role where we occasionally get the error "Unable to read data from the transport connection: An established connection was aborted by the software in your host machine". This error occurs when we are connecting to outside resources like google auth servers. A few people have recommended disabling the firewall\antivirus on the server. I'm just wondering what kind of security risk we would take by doing this. The server doesn't have iis installed but would it be vulnerable to hacking without the firewall? Thanks

    Read the article

  • Linq To SQL - Specified cast is not valid - SingleOrDefault()

    - by NullReference
    I am trying to do the following... Request request = (from r in db.Requests where r.Status == "Processing" && r.Locked == false select r).SingleOrDefault(); It is throwing the following exception... Message: Specified cast is not valid. StackTrace: at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) at System.Data.Linq.DataQuery1.System.Linq.IQueryProvider.Execute[S](Expression expression) at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable1 source) at GDRequestProcessor.Worker.GetNextRequest() Can anyone help me? Thanks in advance!

    Read the article

  • How to use the LINQ where expression?

    - by NullReference
    I'm implementing the service \ repository pattern in a new project. I've got a base interface that looks like this. Everything works great until I need to use the GetMany method. I'm just not sure how to pass a LINQ expression into the GetMany method. For example how would I simply sort a list of objects of type name? nameRepository.GetMany( ? ) public interface IRepository<T> where T : class { void Add(T entity); void Update(T entity); void Delete(T entity); void Delete(Expression<Func<T, bool>> where); T GetById(long Id); T GetById(string Id); T Get(Expression<Func<T, bool>> where); IEnumerable<T> GetAll(); IEnumerable<T> GetMany(Expression<Func<T, bool>> where); } public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where) { return dbset.Where(where).ToList(); }

    Read the article

  • Access Control inside GridView Pager Template - ASP.NET

    - by NullReference
    Hi, I am trying to access a LinkButton that is inside a PagerTemplate in a GridView. However, I am getting a NullReferenceException and I don't know what I am doing wrong here. I have tried the following... ((LinkButton)GridView1.BottomPagerRow.FindControl("lnkbtnPrevious")); ((LinkButton)GridView1.FindControl("lnkbtnPrevious")); Can someone please help? Thanks!

    Read the article

  • How to override [Authorize] attribute in the MVC Web API?

    - by NullReference
    I have a MVC Web Api Controller that uses the [Authorize] attribute at the class level. This makes all of the api methods require authorization but I'd like to create an attribute called [ApiPublic] that overrides the [Authorize] attribute. There is a similar technique described here for normal MVC controllers. I tried creating an AuthorizeAttribute based of the System.Web.Http.AuthorizeAttribute but none of the overridden events are called if I put it on a api method that has the [Authorize] at the class level. Anyone have an idea how to override the authorize for the web api? [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class ApiPublicAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext) { base.HandleUnauthorizedRequest(actionContext); } public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext) { base.OnAuthorization(actionContext); } protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext) { return true; } }

    Read the article

  • How to create a dynamic number of possibly children objects using partial views?

    - by NullReference
    I have a parent object that contains a property that is a list of children objects. I'd like to have it so that when the form loads to create the parent object a partial view is used to create the list of child objects. The problem is I have to idea how to have the list of children object populated. I can do one object ok, but a dynamic list of possible children is difficult. Any ideas? @Html.RenderPartial("_CreateChild", Model.Children); public class Parent { private List<Child> _list; public Guid Id { get; set; } public List<Child> Children { get { return _list; } set { _list = value; } } public Parent() { _list = new List<Child>(); } }

    Read the article

  • How do I avoid boxing/unboxing when extending System.Object?

    - by Robert H.
    I'm working on an extension method that's only applicable to reference types. I think, however, it's currently boxing and unboxing the the value. How can I avoid this? namespace System { public static class SystemExtensions { public static TResult GetOrDefaultIfNull<T, TResult>(this T obj, Func<T, TResult> getValue, TResult defaultValue) { if (obj == null) return defaultValue; return getValue(obj); } } } Example usage: public class Foo { public int Bar { get; set; } } In some method: Foo aFooObject = new Foo { Bar = 1 }; Foo nullReference = null; Console.WriteLine(aFooObject.GetOrDefaultIfNull((o) => o.Bar, 0)); // results: 1 Console.WriteLine(nullReference.GetOrDefaultIfNull((o) => o.Bar, 0)); // results: 0

    Read the article

  • Telerik ASP.NET AJAX - Ajax Update Label with dynamic created Docks

    - by csharpnoob
    Hi, i try to Update a simple Label on Close Event of dynamic created RadDock. Works fine so far, Label gets the correct values but doesnt updates it. RadDock dock = new RadDock(); dock.DockMode = DockMode.Docked; dock.UniqueName = Guid.NewGuid().ToString(); dock.ID = string.Format("RadDock{0}", dock.UniqueName); dock.Title = slide.slideName; dock.Text = string.Format("Added at {0}", DateTime.Now); dock.Width = Unit.Pixel(300); dock.AutoPostBack = true; dock.CommandsAutoPostBack = true; dock.Command += new DockCommandEventHandler(dock_Command); ... void dock_Command(object sender, DockCommandEventArgs e) { Status.Text = "Removed " + ((RadDock)sender).Title + " " + ((RadDock)sender).Text; } I tried to do this: RadAjaxManager1.AjaxSettings.AddAjaxSetting(dock, Status, null); while creating the docks, but on runtime i get a NullReference Excepetion. On a Button registered with the RadAjaxManager it works to show the value assigned by dock_command. protected void Button1_Click(object sender, EventArgs e) { Status.Text = Status.Text; } UPDATE: The RadAjaxManager was created with integrated Wizzard of VS2008. Can't select the Docks, because the are generated while runtime. On Backend its included in AutoCompletion, so the NullReference has nothing to do with the AjaxManager itself. Like i said, works fine with the Button. <telerik:RadAjaxManager ID="RadAjaxManager1"> <telerik:AjaxSetting AjaxControlID="Button1"> <UpdatedControls> <telerik:AjaxUpdatedControl ControlID="Label1"></telerik:AjaxUpdatedControl> </UpdatedControls> </telerik:AjaxSetting>

    Read the article

  • Shaders with pygtkglext

    - by qba
    Do someone know how to get glsl shaders work in gtk-opengl window? With glut all glCreateProgram etc. functions works, but when I tried to put the same gl code into pygtkglext window, its complaining about NullReference: OpenGL.error.NullFunctionError: Attempt to call an undefined function glCreateProgram, check for bool(glCreateProgram) before calling So then I from OpenGL.GL.ARB.shader_objects import *, but the result is similar: OpenGL.error.NullFunctionError: Attempt to call an undefined function glCreateProgramObjectARB, check for bool(glCreateProgramObjectARB) before calling Any idea will be useful.

    Read the article

  • Disposing the members that implement IDisposable.

    - by Amby
    In my Dispose methods (like the one below), everytime i want to call someObj.Dispose() i also have a check for someObj!=null. Is that because of bad design on my part? Is their a cleaner way to ascertain that Dispose of all the members (implementing IDisposable) being used in an object is called without having a risk of NullReference exception ? protected void Dispose(bool disposing) { if (disposing) { if (_splitTradePopupManager != null) { _splitTradePopupManager.Dispose(); } } } Thanks for your interest.

    Read the article

  • InvokeMember("click") webBrowser help

    - by Tom
    I am trying to automate a web page via the weBrowser and the button that i'm trying to click has no ID only a value. here's the html code for it: Accept I can't useGetElementById as the button has no ID. If I do HtmlElement goButton = this.webBrowser1.Document.All["Accept"]; goButton.InvokeMember("click"); My script stops showing a nullreference error highlighting the "goButton.InvokeMember("click");" If I do var inputControls = (from HtmlElement element in webBrowser1.Document.GetElementsByTagName("input") select element).ToList(); HtmlElement submitButton = inputControls.First(x = x.Name == "Accept"); My script give me an "Sequence contains no matching element" error at the "HtmlElement submitButton" line and sometimes the page has more than one of these Accept buttons, so I would need to be able to tell the difference between each one as well or at least be able to click on one without the script breaking Any help with this will be greatly appreciated

    Read the article

  • Problem passing ELMAH log id to Custom Error page in ASP.NET

    - by Ronnie Overby
    I am using ELMAH to log unhandled exceptions in an ASP.NET Webforms application. Logging is working fine. I want to pass the ELMAH error log id to a custom error page that will give the user the ability to email an administrator about the error. I have followed the advice from this answer. Here is my global.asax code: void ErrorLog_Logged(object sender, ErrorLoggedEventArgs args) { Session[StateKeys.ElmahLogId] = args.Entry.Id; // this doesn't work either: // HttpContext.Current.Items[StateKeys.ElmahLogId] = args.Entry.Id; } But, on the Custom error page, the session variable reference and HttpContext.Current.Items are giving me a NullReference exception. How can I pass the ID to my custom error page?

    Read the article

  • Activator.CreateInstance fails in Windows Service

    - by kbe
    I have an issue with a Windows Service which throws a NullReference exception whenever I try to use var myType = Activator.CreateInstance(typeof(MyType)) There is no problem whenever I run the exact same code in a console window - and after debugging the obvious "which user is running this code" I doubt that it is a mere fact of changing the user running the service as I've tried to run the service using the computer's Administrator account as well as LocalSystem. I'm suspecting a Windows Update fiddling with default user rights but that's a bit of a desperate guess I feel. Remember: The type and assembly exist and works fine - otherwise I wouldn't be able to run the code in a console window. It is only when running in the context of a Windows Service I get an error. The question is: Can I in any way impersonate i.e. LocalSystem in a unittest by creating a GenericPrincipal (how would that GenericPrincipal look)?

    Read the article

  • What causes exception in string.concat

    - by Budda
    Here are few classes: public class MyItem : ParamOut { public string Code { get { return _quoteCode; } } public InnerItem[] Skus { get { return _skus; } } public PriceSummary Price { get { return _price; } } public override string ToString() { return string.Concat("Code=", Code, "; SKUs=[", Skus != null ? "{" + string.Join("},{", Array.ConvertAll(Skus, item => item.ToString())) + "}" : "", "]" , "; Price={", Price.ToString(), "}", base.ToString() ); } ... } public abstract class ParamOut { public override string ToString() { return null; } public string ErrorMessage { get; set; } } Here is calling functionality: { MyItem item = new MyItem{ ErrorMessage = "Bla-bla-bla" }; string text = item.ToString(); } I am getting NullReference exception inside of 'ToString()' method (each property of item variable is null). Question: Q1. what overload of string.Concat will be called in this case? I have 9 parameters, so I guess one of the following: public static string Concat(params Object[] args) or public static string Concat(params string[] values) But which of them? Q2. Why exception is generated? Shouldn't 'null' be converted into something like 'null' or "" (empty string)? Thanks a lot!

    Read the article

  • Using LinqExtender to make OData feed fails

    - by BurningIce
    A pretty simple question, has anyone here tried to make a OData feed based on a IQueryable created with LinqExtender? I have created a simple Linq-provider that supports Where, Select, OrderBy and Take and wanted to expose it as an OData Feed. I keep getting an error though, and the Exception is a NullReference with the following StackTrace at System.Data.Services.Serializers.Serializer.GetObjectKey(Object resource, IDataServiceProvider provider, String containerName) at System.Data.Services.Serializers.Serializer.GetUri(Object resource, IDataServiceProvider provider, ResourceContainer container, Uri absoluteServiceUri) at System.Data.Services.Serializers.SyndicationSerializer.WriteEntryElement(IExpandedResult expanded, Object element, Type expectedType, Uri absoluteUri, String relativeUri, SyndicationItem target) at System.Data.Services.Serializers.SyndicationSerializer.<DeferredFeedItems>d__0.MoveNext() at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteItems(XmlWriter writer, IEnumerable`1 items, Uri feedBaseUri) at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteFeedTo(XmlWriter writer, SyndicationFeed feed, Boolean isSourceFeed) at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteFeed(XmlWriter writer) at System.ServiceModel.Syndication.Atom10FeedFormatter.WriteTo(XmlWriter writer) at System.Data.Services.Serializers.SyndicationSerializer.WriteTopLevelElements(IExpandedResult expanded, IEnumerator elements, Boolean hasMoved) at System.Data.Services.Serializers.Serializer.WriteRequest(IEnumerator queryResults, Boolean hasMoved) at System.Data.Services.ResponseBodyWriter.Write(Stream stream) I've kinda narrowed it down to a issue where LinqExtender wraps every returned object, so that my object actually inherits itself - thats at least how it looks like in the debugger. These two queries are basicly the same. The first is the legacy-api where the OrderBy and Select is regular Linq to Objects. The second query is a "real" linq-provider made with LinqExtender. var db = CalendarDataProvider.GetCalendarEntriesByDate(DateTime.Now, DateTime.Now.AddMonths(1), Guid.Empty) .OrderBy(o => o.Title) .Select(o => new ODataCalendarEntry(o)); var query = new ODataCalendarEntryQuery() .Where(o => o.Start > DateTime.Now && o.End < DateTime.Now.AddMonths(1)) .OrderBy(o => o.Title); When returning db for the OData feed everything is fine, but returning query throws a NullRefenceException. I've tried all kind of tricks and even tried to project all the data into a new object like this, but still the same error return query.Select(o => new ODataCalendarEntry { Title = o.Title, Start = o.Start, End = o.End, Name = o.Name });

    Read the article

  • Foreign key relationships in Entity Framework

    - by Anders Svensson
    I'm trying to add an object created from Entity Data Model classes. I have a table called Users, which has turned into a User EDM class. And I also have a table Pages, which has become a Page EDM class. These tables have a foreign key relationship, so that each page is associated with many users. Now I want to be able to add a page, but I can't get how to do it. I get a nullreference exception on Users below. I'm still rather confused by all this, so I'm sure it's a simple error, but I just can't see how to do it. Also, by the way, the compiler requires that I set PageID in the object initializer, even though this field is set to be an automatic id in the table. Am I doing it right just setting it to 0, expecting it to be updated automatically in the table when saved, or how should I do that? Any help appreciated! The method in question: private Page GetPage(User currentUser) { string url = _request.ServerVariables["url"].ToLower(); var userPages = from p in _context.PageSet where p.Users.UserID == currentUser.UserID select p; var existingPage = userPages.FirstOrDefault(e => e.Url == url); //Could be combined with above, but hard to read? if (existingPage != null) return existingPage; Page page = new Page() { Count = 0, Url = _request.ServerVariables["url"].ToLower(), PageID = 0, //Only initial value, changed later? }; _context.AddToPageSet(page); page.Users.UserID = currentUser.UserID; //Here's the problem... return page; }

    Read the article

  • Null reference but it's not?

    - by Clint Davis
    This is related to my previous question but it is a different problem. I have two classes: Server and Database. Public Class Server Private _name As String Public Property Name() As String Get Return _name End Get Set(ByVal value As String) _name = value End Set End Property Private _databases As List(Of Database) Public Property Databases() As List(Of Database) Get Return _databases End Get Set(ByVal value As List(Of Database)) _databases = value End Set End Property Public Sub LoadTables() Dim db As New Database(Me) db.Name = "test" Databases.Add(db) End Sub End Class Public Class Database Private _server As Server Private _name As String Public Property Name() As String Get Return _name End Get Set(ByVal value As String) _name = value End Set End Property Public Property Server() As Server Get Return _server End Get Set(ByVal value As Server) _server = value End Set End Property Public Sub New(ByVal ser As Server) Server = ser End Sub End Class Fairly simple. I use like this: Dim s As New Server s.Name = "Test" s.LoadTables() The problem is in the LoadTables in the Server class. When it hits Databases.Add(db) it gives me a NullReference error (Object reference not set). I don't understand how it is getting that, all the objects are set. Any ideas? Thanks.

    Read the article

1