Thursday, May 5, 2011

Extending DataContext entities - using InsertOnSubmit(this) inside "child" class

I am extending this DataContext entity, which looks sort'a like this:

namespace Entities
{
    public class User
    {
        public Int32 Id { get; set; }
        public String Username { get; set; }
    }
}

.. Like so:

public class User : Entities.User
{
    new public Int32 Id
    {
        get { return base.Id; }
    }


    public void Insert()
    {
        using (var dc = new DataContext())
        {
/*
The "this" keyword should match the type that InsertOnSubmit() expects.
And it does. But I get the following error:

System.NullReferenceException: {"Object reference not set to an instance
of an object."}
*/
            dc.Users.InsertOnSubmit(this); // Exception occurs here

            dc.SubmitChanges();
        }
    }
}

I am using the custom User class like so:

var u = new User { Username = "Test" };

u.Insert();

What I don't get is this: I have instantiated the class, so why am I getting a NullReferenceException?


Update:


Extending entity class: overriding a property with an enumerator while still being able to use the "this" keyword on the Insert/Update and DeleteOnSubmit methods on a DataContext instance

enum AccessLevels
{
    Basic,
    Administrator
}


namespace Entities
{
    public class User
    {
        public Int32 Id { get; set; }
        public String Username { get; set; }
        public Int32 AccessLevel { get; set; }
    }
}

How would I extend or alter the above entity class and implement the AcessLevels enumerator, replacing the AccessLevel property?--this without altering the signature of the entity class, so I'm able to use the "this" keyword on Insert/Update and DeleteOnSubmit methods on a DataContexts.

From stackoverflow
  • You can't extend LINQ-to-SQL entity types in this way via inheritance - you should instead use a partial class to add extra methods to the existing generated entity. Because LINQ-to-SQL supports inheritance (for discriminated tables, etc), it expects an exact match to a known entity type - not unexpected subclasses.

    i.e.

    namespace Entities {
        partial class User {
            /* your extra method(s) here */
        }
    }
    

    In the above, this is combined with the partial class in the designer.cs to create you type.

    The other way to do this (if partial class isn't an option) is via an extension method.

    static class EntityExtensions {
        public static void SomeMethod(this User user) {...}
    }
    

    If there are methods common between types, you can do this by declaring an interface, using extension methods on that interface, and using partial classes to add the interface to the specific types:

    namespace Entities {
        partial class User : IFunkyInterface {
            /* interface implementation, if necessary */
        }
    }
    
    static class EntityExtensions {
        public static void SomeMethod(this IFunkyInterface obj)
        {...}
    }
    

    or if you need to know the type:

    static class EntityExtensions {
        public static void SomeMethod<T>(this T obj)
              where T : class, IFunkyInterface
        {...}
    }
    
    roosteronacid : Good advice. Only.. I need to override a property of the entity class, which is not possible using partial classes, so I guess I'm forced to do extension methods--only; how can I do that? How can I add specific methods to specific entity classes? Could you update your answer?
    Marc Gravell : What do you mean "override a property"? There are existing partial methods for most of the common before-change/after-change scenarios. I'll add an example for extension methods.
    roosteronacid : Hey Marc. Updated my question. I'd appreciate your take on it.
  • Re the enum edit (added as a second answer to keep things simple)...

    Firstly - is there a direct 1:1 mapping between the enum and the values? For example, if Basic is 7 and Administrator is 12, then:

    enum AccessLevels
    {
        Basic = 7,
        Administrator = 12
    }
    

    Then change the type of that property in the dbml (via the designer) from int to your (fully-qualified) enum: Entities.AccessLevel. LINQ-to-SQL supports enums either as direct integer mappings, or as direct string mappings.

    If this isn't possible (more complex scenerios), you can isolate the storage (int) and object-oriented (enum) models; rename the property to AccessLevelStorage (or anything else you like), and in a partial class do the mapping:

    partial class User {
        public AccessLevel AccessLevel {
            get {
                switch(AccessLevelStorage) {
                    case 1: return AccessLevelStorage.Foo;
                    ... etc
                    default: ...throw an exception?
                }
             }
             set {
                switch(value) {
                    case AccessLevel.Foo: AccessLevelStorage = 1; break;
                    ...etc
                    default: ...throw an exception?
                }
             }
    }
    

    The only caveat here is that LINQ queries will only work against the storage properties - not the custom mapped property. If you do your queries at the level that declares the context, you can change the access of the storage property to internal - but if you do queries outside of this assembly you'll need to leave is public. You might want to add [Browsable(false)] to stop it appearing in UI models, but that is about it.

    roosteronacid : Excellent! First option in my case. Thanks a bunch Marc :)

Changing JTable cell color

This is driving me absolutely insane.

I know that, to change the formatting of table cells with JTable, I have to use my own renderer. But I cannot seem to implement this properly.

This is my current setup:

public class MyClass
{
    public static void main(String args[])
    {
     JTable myTable = new JTable(10, 10);
     myTable.setDefaultRenderer ([I dont know what to put here], new CustomRenderer());
    }
}

class CustomRenderer extends DefaultTableCellRenderer 
{
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
     Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

     // Formatting
     return c;
    }
}

What do I need to use for the first parameter of setDefaultRenderer? The API just says 'class'. I have no idea what to put there.

Could someone just explain, in the simplest of terms, how I go about implementing this? Please provide an example of how I can change the formatting from within the main() method as well.

From stackoverflow
  • In the first parameter for setDefaultRenderer, put the class literal for the Class that you want to override rendering. I.e., if your data consist all of strings, you can put

    myTable.setDefaultRenderer(String.class, new CustomRenderer());
    

    If your data also consists of values with BigDecimal or Integer as classes, you have to invoke that method several times for each class type (BigDecimal.class or Integer.class in each case).

    And finally, to change the background color you do this in your renderer:

    class CustomRenderer extends DefaultTableCellRenderer 
    {
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
        {
            Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            c.setBackground(new java.awt.Color(255, 72, 72));
            return c;
        }
    }
    
    Josh Leitzel : This doesn't seem to work for me. The only thing I've done is invoke the setDefaultRenderer method and created the CustomRenderer class. Is there something else I need to be doing to get this to work?
    Camilo Díaz : Can you post your entire code here: http://www.rafb.net/paste/ ?
    Josh Leitzel : I got it working by using Object.class instead of String.class. Not sure why this was necessary, though, because all of my data were strings. Thank you for your help!
    Josh Leitzel : Am I not allowed to change the renderer inside a listener? I want to re-format the table when a button is pressed.
    KitsuneYMG : You need to use Object.class because you created a JTable w/o passing in a TableModel. The default table model created returns Object.class for each columns type. See: TableModel::getColumnClass(int col)
    pypmannetjies : Where do I use it? Say I now want to change a table cell's colour when I click on it?
  • For brief code kindly to this site

    http://apachejava.blogspot.com/2010/08/jtable-change-specific-complete-row.html

.Net/Mono Singleton (Service/Server?) in C# - detect if my .net app is already running and pass command-line args to it.

I'd like to create a simple singleton commandline application (a service?) in C# that when it was run, it checked to see if it was already running, and if so, it passed the command-line args to the already running instance and closed itself. Now in the already running instance it would receive the command-line args through an event like "delegate void Command(string[] args);" or something like that, so I can manage command-line through one application via events.

For instance in photoshop, when you open a picture for the first time, it loads a new instance photoshop, but when you open a second picture, it checks to see if an instance of photoshop is already running, and if it is, it passes the picture to the already loaded instance of photoshop so it can avoid the costly load-time of photoshop all over again...

Or in the web browser, you can set it so if you open a new .html file, it opens it up in a new tab, not a new window instance.

or many text editors have settings to only allow one instance of the text editor open and when a new file is opened, it's loaded in a new tab, not a new window...

many music players like winamp do this too...

I am going to eventually be setting this up as a service, so it should be constantly listening for command-line args later, but for now it's mostly so that I can manage the opening of files of a specific type together in one singleton application, or have other applications pass command-line arguments of files they want to be opened...

Also, if you know a better way or an api in .Net to re-rout all command-line args passed, to an event of a service that is always running, I can work with that... but I'd also like to keep this cross-platform so it can run in Linux/Mac on Mono if that's possible, without having to manage two or more code-bases...

From stackoverflow
  • We did something simillar using although for a very different purpose using .net remoting on 1.0 / 1.1 framework. Basically we'd use a semaphore to ensure we were the only running instance. You'll want to target the global namespace, if you want to have only one instance per machine or the local if you want one per user session (In terminal service and fast user switching scenarios).

    If you can lock the semphore, you will setup remoting and start listening for events, and then continue on with your code.

    if you can't lock then you can asssume you have another running instance in which case you'll open up a remoting channel to the other instance pass the args and shutdown.

  • You could try using a named mutex (naming it will make it system wide, and easily identifiable). With the mutex, you can either run the instance (if no mutex exists with the name), or you can open the existing instance and pass in your parameters. Apologies for no code sample, writing this from my phone.

    Edit: nvrmnd. Just reread the post, and I don't think this will work for you going cross platform.

  • Visual basic has this built-in. Take a look at:

    Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase -- Public Event StartupNextInstance

    Keivan : Microsoft.VisualBasic is Evil!!! ;)
  • This is the article i used to implement the exact functionality that you are looking for, it allows you to transfer command line arguments as well.

    Single-Instance C# Application - for .NET 2.0

Storage of sparse numerical data (e.g. inverted index) - any conventions?

Is there an accepted way of storing and accessing sparse numerical data (such as a search engine's inverted index / term by document matrix)? An RDBMS seems inappropriate for this kind of data, but it would be good to have it stored in some kind of database (saved to disk, running as a server, etc). Is there an accepted solution for this kind of problem (such as an existing database capable of supporting this kind of model)? Anyone know how Google stores and accesses their indexes so fast? Thanks!

From stackoverflow
  • Have a look here for more info on Google and links to more info.

does mysql 5.4 has a linux 32 bit version?

Can MySQL 5.4 beta be compiled for 32-bit processors under Linux?

From stackoverflow

C++ how to call a parent class method from contained class?

I am trying to make a call to a Parent class method from a contained object, but have no luck with the following code. What is the standard way to do it?

I have searched around and this seems to work for inherited objects, but not for contained objects. Is it right to call it a Parent class even? Or is it called an Owner class?

class Parent{
private:
  Child mychild;

public:
  void doSomething();
}

class Child{
public:
  void doOtherThing();
}

void Child::doOtherThing(){
  Parent::doSomething();
}
From stackoverflow
  • A contained object has no special access to the class that contains it, and in general does not know that it is contained. You need to pass a reference or a pointer to the containing class somehow - for example:

    class Child{
    public:
      void doOtherThing( Parent & p );
    };
    
    void Child::doOtherThing( Parent & p ){
       p.doSomething();
    }
    
  • If the child needs to interact with the parent, then it will need a reference to that object; at present, the child has no notion of an owner.

  • The child has no connection to the parent class at all. You'll have to pass 'this' down to the child (probably in the constructors) to make this work.

How I detect whether or not a file has been renamed using Cocoa?

I'm building a utility application that synchronizes files across two systems for Mac OSX. I need to detect when a file has been renamed but is otherwise the same file. How do I do this in Cocoa?

From stackoverflow
  • You can look at the inode number (NSFileSystemFileNumber in the attributes returned by NSFileManager), which would cover simple rename cases.

  • There's no simple answer; you need to figure out the best strategy for your app.

    At a simple level there is working with the file system number. You can grab this using NSFileSystemFileNumber. Probably better for the job though is to use FSRef. It's a C API but relatively straightforward, and has a method for comparing to FSRefs for equality.

    But, there are plenty of applications which perform a save operation by replacing the file on disk, changing its file number. This could well upset your code. So consider using aliases. This is the same system as the Finder uses to keep track of the target of an alias file. Use either the Alias Manager (C API), or one of the open source Objective-C wrappers (e.g. NDAlias or BDAlias). An alias will do its best to maintain a reference to a file by both path and file number.