Monday, February 21, 2011

IDL declaration (in C++) for a function that will take a C-style array from C#

I am working with an existing code base made up of some COM interfaces written in C++ with a C# front end. There is some new functionality that needs to be added, so I'm having to modify the COM portions. In one particular case, I need to pass an array (allocated from C#) to the component to be filled.

What I would like to do is to be able to pass an array of int to the method from C#, something like:

// desired C# signature
void GetFoo(int bufferSize, int[] buffer);

// desired usage
int[] blah = ...;
GetFoo(blah.Length, blah);

A couple of wrenches in the works:

  • C++/CLI or Managed C++ can't be used (COM could be done away with in this case).
  • The C# side can't be compiled with /unsafe (using Marshal is allowed).

The COM interface is only used (an will only ever be used) by the C# part, so I'm less concerned with interoperability with other COM consumers. Portability between 32 and 64 bit is also not a concern (everything is being compiled and run from a 32 bit machine, so code generators are converting pointers to integers). Eventually, it will be replaced by just C++/CLI, but that is a ways off.


My initial attempt

is something similar to:

HRESULT GetFoo([in] int bufferSize, [in, size_is(bufferSize)] int buffer[]);

And the output TLB definition is (seems reasonable):

HRESULT _stdcall GetFoo([in] int bufferSize, [in] int* buffer);

Which is imported by C# as (not so reasonable):

void GetFoo(int bufferSize, ref int buffer);

Which I could use with

int[] b = ...;
fixed(int *bp = &b[0])
{
    GetFoo(b.Length, ref *bp);
}

...except that I can't compile with /unsafe.


At the moment

I am using:

HRESULT GetFoo([in] int bufferSize, [in] INT_PTR buffer);

Which imports as:

void GetFoo(int bufferSize, int buffer);

And I need use use it like:

int[] b = ...;
GCHandle bPin = GCHandle.Alloc(b, GCHandleType.Pinned);
try
{
    GetFoo(b.Length, (int)Marshal.UnsafeAddrOfPinnedArrayElement(b, 0));
}
finally
{
    bPin.Free();
}

Which works..., but I'd like to find a cleaner way.


So, the question is

Is there an IDL definition that is friendly to the C# import from TLB generator for this case? If not, what can be done on the C# side to make it a little safer?

From stackoverflow
  • I don't know much about C# COM operability, but have you tried using SAFEARRAY(INT_PTR) or something similar?

    Corey Ross : I'll look into that
  • Hmmm... I've found some information that gets me closer...

    Marshaling Changes - Conformant C-Style Arrays

    This IDL declaration (C++)

    HRESULT GetFoo([in] int bufferSize, [in, size_is(bufferSize)] int buffer[]);
    

    Is imported as (MSIL)

    method public hidebysig newslot virtual instance void GetFoo([in] int32 bufferSize, [in] int32& buffer) runtime managed internalcall
    

    And if changed to (MSIL)

    method public hidebysig newslot virtual instance void GetFoo([in] int32 bufferSize, [in] int32[] marshal([]) buffer) runtime managed internalcall
    

    Can be used like (C#)

    int[] b = ...;
    GetFoo(b.Length, b);
    

    Exactly what I was gunning for!

    But, are there any other solutions that don't require fixing up the MSIL of the runtime callable wrapper that is generated by tlbimport?

  • So you're asking for an IDL datatype that is 32-bits on a 32-bit machine and 64-bits on a 64-bit machine. But you don't want the marshaling code to treat it like a pointer, just as an int. So what do you expect to happen to the extra 32-bits when you call from a 64-bit process to a 32-bit process?

    Sound like a violation of physics to me.

    If it's inproc only, see the bottom of this discussion: http://www.techtalkz.com/vc-net/125190-how-interop-net-client-com-dll.html.

    The recommendation seems to be to use void * instead of intptr and flag with the [local] so the marshaller doesn't get involved.

    Corey Ross : I would like them all to be INT_PTR, however tlbimport is converting them to int, not me. If I do need to go the MSIL fixup route, I can correct it to System.IntPtr there.
    Tony Lee : What I don't get is why you're using INT_PTR when your solution will only work in a 32-bit process?
    Corey Ross : The COM side is definitely 32bit, so initially that signature was chosen by following similar conventions to existing code. But, you are right about the managed side, I should explicitly specify a 32bit int (which tlbimport is doing).
    Corey Ross : [local] void* does import as System.IntPtr, but the other issues still exist. Unfortunately this 32/64 bit portability tangent doesn't address the C-style array semantics that I am trying to achieve.

How to show compulsory fields on a windows form

How should I show users which fields are compulsory in a windows forms application.

I have considered changing the label color or maybe the background color of the text box.

I use an error provider to show a red exclamation mark next to the field, however this is only visible after they have clicked the save button.

From stackoverflow
    • Asterisk or icon to the side of control
    • Red border when required validation fails (when user tries to save)
    • Bold Labels
    • Different background color for required controls (perhaps only when user tries to save)
    Rob : A firm, but not too thick red border sounds good to me.
    Jason Jackson : ... or any color that is complementary to the application's color scheme but stands out.
    John Rudy : What I've found works best is a different background for the controls, always visible. The color should be pastel, often yellow as seen in browsers. This usually looks OK on any given UI theme, and makes it eminently clear to the user what is/isn't required without taking up extra visual space.
    Argalatyr : (@John Rudy) Like my answer just below?
    Robert C. Barth : Using JUST a color to indicate required fields is usually not the best practice from an HCI perspective because: 1. blind users will never see it, and 2. color-blind users (of which there are way more than you think) /may/ not see it.
  • Yellow background would make it similar to many web forms. No idea whether there are any standards for Windows per se, though if there are I doubt they are widely used.

  • Use the errorprovider extension control.

    This places a red cross next to the control with a tooltip message.

  • I would use the ErrorProvider control, possibly with a different icon to represent "required" as opposed to "in error". I would also ensure the fields start with error icon shown next to them and the icon should only disappear once data has been provided for that field.

    Only doing validation/notification of missing data when the user tries to save seems way too late.

  • Something to consider is what users are accustomed to seeing for required fields. While not graphically spectacular, placing a simple asterisk next to required field is a very ubiquitous solution.

What is the proper order for installing Microsoft software on a developer workstation?

I've done this a million times ... setting up a developer work station.

Is there a best practices, or installation checklist for installing Microsoft development software on a work station? What about applying updates and/or service packs? Is there a specific order for doing this, in hopes of minimizing any install issues.

Our current software library consists of:

  • Visual Studio 2003
  • Visual Studio 2008
  • SQL Server 2005
  • Microsoft Office 2007

We do use some other tools, but I usually hold off on installing them once I get a good build from Microsoft ... whether a good build is possible or not is another topic! =)

Also, do you use any software like Ghost to create images of work station? Some easy way to restore your work station.

From stackoverflow
  • I tend to go in chronological order. The oldest software to the most recent.

    In your case I would do something like

    1. Office 2007 (I usually install office first)
    2. VS2003
    3. Install VS2003 updates through Microsoft update
    4. SQL Server 2005
    5. Install SQL Server 2005 through Microsoft Update

    And so on...

    When the setup is over and the machine is configured I do a full base image with Acronis True Image.

    Mitchel Sellers : It is important to remember that IIS MUST be installed first....
    Pascal Paradis : This is true in the case of machine used for web development only. Am I wrong?
  • You should be able to install each piece of software regardless of the order you install it in. That being said, if you want to be 'safe', start with the lowest version of each and work you way up, installing the updates/SP's as you go along.

    mattruma : I'm not a big fan of **should**.
  • I don't use Ghost as none of the workstations I setup are ever identical.

    As far as install order, I would do:

    • Office 2007
    • SQL Server 2005
    • VS 2003
    • VS 2008
  • I'd do:

    • Operating System
    • Anti-virus/security software (if applicable)
    • Office
    • .Net framework runtimes
    • Security Updates
    • SQL Server
    • Visual Studio
    • Source control client
    • Any other tools (Notepad++, ftp client, etc)
    • Security Updates

    SQL Server vs Visual studio may be backwards, but that probably doesn't matter.

    That just leaves the order for visual studio installs. In general you want to install the older products first. However, there may be a situation where that's not the case. If you have, say, VS2008 Standard and VS2003 Professional you might want to install the professional edition later. But I haven't been able to play with that particular scenario.

    Finally, I normally prefer to apply all patches at once. It saves time. However, I want to make sure my .Net runtimes are up to date before installing the developement tools, and in the case of multiple editions of Visual Studio (or any other complicated package) I prefer to make sure each instance of the software is fully up to date before installing the next.

  • I would use the following and this order IS KEY if you want to do ASP.NET Development without issue.

    • Operating System
    • IIS for the OS <- If not done before VS, issues can be had
    • OS Updates
    • Office
    • Office Updates
    • SQL Server and tools
    • SQL Server Updates
    • VS 2003
    • VS 2003 Updates
    • VS 2005 (DON'T install SQL Express)
    • VS 2005 Updates
    • VS 2008
    • VS 2008 Updates
    • Any third party tools for development environments (Telerik, DevExpress, etc)

    I have found that with this format, you will NOT have any issues, but if you change the order, I have had bad things happen before. Especially important is the IIS setup piece!

    John Rudy : As an add to this: If you're also installing 3rd party components or VS add-ins, don't install them until the rest of the stack is up and running.
    Mitchel Sellers : Very valid point!
    Ken Ray : I believe you should install SQL Server and associated tools AFTER VS 2005 - then VS 2005 has the various SQL Server add ins.
    Nick Stinemates : God this is so dumb. So happy I am not a windows developer.
    Mitchel Sellers : Ken, VS 2005 by default installs SQL Server Express, so it is best to have it installed FIRST, that way the proper templates are added when you install. IF SQL is not there, they will not install, at least that is what I have noticed in my last 5-10 workstation builds
    wizlb : This guy has a good explanation of why SQL 2005 should be installed before VS 2005 http://geekswithblogs.net/ingrid/archive/2006/02/03/68116.aspx (and as a Windows dev, I'm glad I don't have to cobble together solutions with buggy unfinished OSS components and I get to use nice tools like VS 2008)
    Wil : I have been having so many problems with SQL 2008, the x64 bit hotfix and more. I was going to start a new question but I don't suppose it is possible to have an update to your post to deal with sql 2008?
    Mitchel Sellers : The install order is the same, just do NOT install SQL with EITHER edition of Visual Studio
    Roger Lipscombe : If you install Visual Studio (with SQL Server 2005 Express), the full-blown SQL Server 2005 installer doesn't bother installing SQL Server Management Studio, so either install SQL Server before VS or exclude SQL Server Express from the VS install. This is probably fixed with SQL Server 2008, although I've not checked.
  • I'm definitely a Ghost addict. At a former work I would spend about 2-3 hours configuring properly everything needed for a user: Windows+patches, Office+patches, Acrobat Reader, etc. Once everything's ready I would create an image of the whole hard drive using Ghost, and store it somewhere (if possible, ZIP it and burn it to a DVD).

    Then, when a new colleague arrived, I had Ghost restore the image onto a new hard drive - this was accomplished in 20 minutes or less! After that, manual work was reduced to:

    • Changing PC's name
    • Changing Windows and Office License numbers (I remember there was a tool at TechRepublic for this, technically it's not illegal)
    • Changing PC's IP address (if you're not using DHCP)
    • Ready!

    All of those steps can be easily scripted, if you wish. Anyway, it's just 10 minutes or less.

    At my current work I'm just a developer so I'm not in charge of preparing machines for new coworkers anymore. However, from this past experience I'd say using Ghost is the fastest and most cost effective way to setup new computers!

    Especially the Windows installation and going to Windows Update - argh!! I really hate loosing so much time at these steps, it can be tolerated if you only do that once.

    mattruma : Do you use Ghost for creating an image of your current workstation?
    Joe Pineda : No, that's handled by another department :D
  • My recommendation is to start with the OS and its updates, then add Office if you need that and then install Virtual PC or VMWare. This way you can separate the different versions (and betas) of all the development stuff into different VPC's. Your real hardware will stay clean and you are able to switch between environments very smoothly.

  • For a web platform, Microsoft has a nice package installer here: http://www.microsoft.com/web/channel/products/WebPlatformInstaller.aspx

    I like using sysprep before imaging a machine so that I can create multiple workstations with the same config

What could cause a .NET WinForms app to close suddently without a dialog?

Our WinForms application has been reported to occasionally just close on its own. It neither shows our own crash error submit dialog nor Windows' error submit dialog, it just closes and is gone, often when the person was afk and not doing anything with the application. It seems to be a semi-rare occurrence, maybe like 2-3 times a month, and it's happened to more than one person. I have no idea where to start with getting a repro case or where to begin tracking this down.

C# .NET 2.0 Reported cases are on Win XP

Anyone have any ideas?

From stackoverflow
  • Exceptions will cause an app to "disappear". Check the Event logs to see if anything was there.

    Check task manager to see if the process is still present when the window disappears. I have had explorer crash and fail to redraw the window until it was Alt-Tabbed or Switched-To (from task manager).

    Dont put it past the users to conveniently forget they are closing the app. You may want to put some logging logic in the app to log user initiated closures. Next time it "disappears" you can check for any log entries.

    Davy8 : The app isn't out in "the wild" yet so I know these users well enough to trust that they didn't close the app themselves (it happens a bit too often for convenient forgetfulness)
    Davy8 : Also the app doesn't create a new instance if there already is another process, and they were able to reopen the app, so it did indeed crash silently, but in general those are good things to check for.
  • You could add some logic in the FormClosing event to ask the user if thats what they really want to do, you can then cancel the closing event and your application will continue to run if all is well. If you keep noticing this problem and it never performs your logic, you're going to have to get your hands dirty in the debugger.

  • Stack overflows due to infinite recursion are a big cause of apps quitting with no warning. Unless you've done something deliberate to cause a silent exit, then unhandled exceptions (other than stack overflow) will normally display some kind of UI before the app quits. Stack overflow is the most common exception (oops, sorry) to this rule.

    Of course, from unmanaged or unsafe code it's almost certainly possible to upset the runtime in the right way to cause a silent exit.

    The suggestions about instrumentation and looking at the Windows event log are good too.

    Davy8 : It sounds like it is most likely a silent crash is the culprit. Thanks

How do I detect "Easter Egg" mode in my Palm OS application?

Since the early days, Palm OS has had a special "easter egg" mode that's enabled by making the right gesture in one of the Preference panels. On current Palm Treo and Centro devices, this is turned on by doing a clockwise swirl above the "Tips" button in the Power panel.

Some applications, like the Blazer web browser, enable special features when easter eggs are active. How can I detect this in my own program?

From stackoverflow
  • The standard system preference for this is prefAllowEasterEggs (see Preference.h). This setting can be accessed using the PrefGetPreference API:

    UInt32 enableEasterEggs = PrefGetPreference(prefAllowEasterEggs);
    

    The value will be non-zero when the user has requested that Easter eggs be available.

Mounting/Unmounting USB disks on Windows

On Windows Server, by default, external USB disks don't always get mounted. I'd like my program (written in C#) to be able to detect external USB disks, identify them, and then mount them.

When it's finished, it should do whatever the programmatic equivalent of "Safely Remove Hardware" in order to flush and unmount the disk.

Any pointers?

From stackoverflow

Is it possible to add to the available parameters of a request (HttpServletRequest)

I want to intercept a request in a filter/servlet and add a few parameters to it. However, the request does not expose a 'setParameter' method and the parameter map when manipulated throws an error saying it is locked. Is there an alternative I can try?

From stackoverflow
  • First you should receive the request and read all its parameters. Then construct another request with the original parameters + the new ones and send it again.

    The HttpServletRequest is immutable and there is no way to change it.

  • I ussualy wrap the original HttpServletRequest into a new CustomHttpServletRequest that acts as a proxy to the original request and then pass this new CustomHttpServletRequest to the filter chain.

    In this CustomHttpServletRequest you can overide the getParameterNames, getParameter, getParameterMap methods to return any parameters you want.

    This is an example of the filter:

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletRequest customRequest = new CustomHttpServletRequest(httpRequest);
        customRequest.addParameter(xxx, "xxx");
        chain.doFilter(customRequest, response);
    }
    
    Vivek Kodira : Thank you :). This worked.
  • Subclass HttpServletRequestWrapper and override the getParameter methods. The description of this class reads:

    Provides a convenient implementation of the HttpServletRequest interface that can be subclassed by developers wishing to adapt the request to a Servlet.

    In the filter, wrap the request in an instance of your subclass.

    Vivek Kodira : Thank you :). This worked.
  • Otherwise, you can use the setAttribute() method which is strongly typed. Therefore, the getAttribute() method can be used ...

    Vivek Kodira : I'm adding this as a property-file driven mechanism that modifies a regular request. Both the UI and the actual servlet cannot be changed to accomodate these requirements - it is transparent.
  • Why don't you just store variables as Request scope attributes instead of trying to append them to the request parameters?

    Vivek Kodira : I'm adding this as a property-file driven mechanism that modifies a regular request. Both the UI and the actual servlet cannot be changed to accomodate these requirements - it is transparent.

Strict HTML Validation and Filtering in PHP

I'm looking for best practices for performing strict (whitelist) validation/filtering of user-submitted HTML.

Main purpose is to filter out XSS and similar nasties that may be entered via web forms. Secondary purpose is to limit breakage of HTML content entered by non-technical users e.g. via WYSIWYG editor that has an HTML view.

I'm considering using HTML Purifier, or rolling my own by using an HTML DOM parser to go through a process like HTML(dirty)->DOM(dirty)->filter->DOM(clean)->HTML(clean).

Can you describe successes with these or any easier strategies that are also effective? Any pitfalls to watch out for?

From stackoverflow
  • User-submitted HTML isn't always valid, or indeed complete. Browsers will interpret a wide range of invalid HTML and you should make sure you can catch it.

    Also be aware of the valid-looking:

    <img src="http://www.mysite.com/logout" />
    

    and

    <a href="javascript:alert('xss hole');">click</a>
    
    Barry Austin : Thanks Ross, these are excellent examples of kinds of input that should be filtered out. But the answer I'm looking for will include methods and solutions also.
    Bobby Jack : The first example (which is a reference to a codinghorror article: http://www.codinghorror.com/blog/archives/001171.html) is not really relevant since the 'hole' depends upon the nature of that URL, rather than the syntax of this particular HTML snippet.
    Barry Austin : There are still useful rules that could be applied to the first one, for example "allow tag only when the src attribute matches the regex /^http:\/\/localsite.com\/uploaded_images\/[\w-]*\.(png|jpg|gif)$/i".
  • The W3C has a big open-source package for validating HTML available here:

    http://validator.w3.org/

    You can download the package for yourself and probably implement whatever they're doing. Unfortunately, it seems like a lot of DOM parsers seem to be willing to bend the rules to allot for HTML code "in the wild" as it were, so it's a good idea to let the masters tell you what's wrong and not leave it to a more practical tool--there are a lot of websites out there that aren't perfect, compliant HTML but that we still use every day.

    porneL : Validation against DTD doesn't protect against XSS at all.
    Ross : Exactly, I don't think that's what Barry meant with validation - think data validation or screening rather than standards validation. This would help against malformed HTML though ;)
  • I've tested all exploits I know on HTML Purifier and it did very well. It filters not only HTML, but also CSS and URLs.

    Once you narrow elements and attributes to innocent ones, the pitfalls are in attribute content – javascript: pseudo-URLs (IE allows tab characters in protocol name - java&#09;script: still works) and CSS properties that trigger JS.

    Parsing of URLs may be tricky, e.g. these are valid: http://spoof.com:xxx@evil.com or //evil.com. Internationalized domains (IDN) can be written in two ways – Unicode and punycode.

    Go with HTML Purifier – it has most of these worked out. If you just want to fix broken HTML, then use HTML Tidy (it's available as PHP extension).

    BlaM : ... hint: http://htmlpurifier.org/
    Barry Austin : Thanks for your answer!
  • I used HTML Purifier with success and haven't had any xss or other unwanted input filter through. I also run the sanitize HTML through the Tidy extension to make sure it validates as well.

Using SQL for cleaning up JIRA database

Has anyone had luck with removing large amount of issues from a jira database instead of using the frontend. Deleting 60.000 issues with the bulktools isnt really feasible.

Last time i tried it, the jira went nuts because of its own way of doing indexes

From stackoverflow
  • How about doing a backup to xml, editing the xml, and reimporting?

    dacracot : I have had success with this method, but never had the guts to try SQL on their schema.
    svrist : The backup takes quite a while too, but this might be a usable idea
  • We got gutsy and did a truncate on the jiraissues table and then use the rebuild index feature on the frontend. It looks like it's working!

finding largest increasing subset of an array (non-contiguous)

How can I find the largest increasing (non-contiguous) subset of an array? For example, if A= array(50,1,4,9,2,18,6,3,7,10) the largest increasing non-contiguous subset is either (1,4,6,7,10) or (1,2,6,7,10). I can intuitively see how to find the subset, but I don't know how to design the algorithm. thanks.

From stackoverflow

Is there an equivalent to String.Split that returns a generic list?

I'd like to do something like this:

Dim Foo as String = "a,b,c,d,e"
Dim Boo as List(of String) = Foo.Split(","c)

Of course Foo.Split returns a one-dimensional array of String, not a generic List. Is there a way to do this without iterating through the array to turn it into a generic List?

From stackoverflow
  • If you use Linq, you can use the ToList() extension method

    Dim strings As List<string> = string_variable.Split().ToList<string>();
    
    Herb Caudill : How exactly do you propose using Linq to query a comma-separated string?
    James Curran : He's not querying it. The ToList() extension method Code Monkey shows in his answer is just part of the class of functionality common known as "Linq" (and is used to support LINQ query, but you can use it for other things)
  • You can use the List's constructor.

    String foo = "a,b,c,d,e";
    List<String> boo = new List<String>(foo.Split(","));
    
    Herb Caudill : Gave answer to @Bob King for answering in VB.NET - thanks.
    Bob King : Sorry mats! No hard feelings!
  • If you don't want to use LINQ, you can do:

    Dim foo As String = "a,b,c,d,e"
    Dim boo As New List(Of String)(foo.Split(","c))
    
  • Do you really need a List<T> or will IList<T> do? Because string[] already implements the latter... just another reason why it's worth programming to the interfaces where you can. (It could be that in this case you really can't, admittedly.)

    IAmCodeMonkey : You can use IList, in fact you should (even though I forgot to in my answer's code example)
    Saif Khan : I agree, although I am trying to get into this habbit.
  • The easiest method would probably be the AddRange method.

    Dim Foo as String = "a,b,c,d,e"
    Dim Boo as List(of String)
    
    Boo.AddRange(Foo.Split(","c))
    
    Herb Caudill : Thanks - this works as well as the accepted answer but is slightly less compact.
    Kyralessa : That code works? It looks to me like it would throw a NullReferenceException.
    amcoder : You're right. I forgot to create the Boo instance.
  • Here is how I am doing it ... since the split is looking for an array of char I clip off the first value in my string.

    var values = labels.Split(" "[0]).ToList<string>();
    

Need help writing a custom BuildListener

I would like to add a BuildListener to my headless build process, which is building an Eclipse product. The docs on how to do this are, shall we say, a bit scanty. I think I need to put my custom jar in a plugin and then use the org.eclipse.ant.core.extraClasspathEntries extension point to make that jar visible to Ant. But everything I have tried results in

 [myClass] which was specified to be a build listener is not an instance of org.apache.tools.ant.BuildListener.

My class implements the BuildListener interface. Various postings seem to indicate that this means my class is visible-to/loaded-by the Plugin classloader rather than the Ant classloader. But I thought the whole point of the extension point was to make jars visible to Ant...

Can anyone shed light on what I'm doing wrong? Additional info: I am trying to run this build from the Eclipse IDE at the moment using the AntRunner application.

From stackoverflow
  • I had this problem when I had two plugins providing an ant.jar.
    Make sure you use the org.apache.ant plugin and that there is no other plugin providing another ant.jar.

    Another thing I just stumbled upon: The jar containing your contribution must not be in the plugins classpath (Runtime -> Classpath).
    See Eclipse Bug 34466

    Revah : Thanks. I had already solved this, but this was indeed the problem. You must be very scrupulous about the location of the contribution.
  • Follow the instructions as for working with contributed tasks and types found here: Developing Ant tasks and Contributed Ant tasks

C# Inheritance

I had a coworker see this the other day and I'm not quite sure why this happened. Can anyone explain it?

We have class A:

using System;
using System.Data;

public class A
{
  protected DataTable _table;

  public A()
  {

  }
}

We have class B that inherits from class A (assume there in the same namespace):

using System;

public class B : A
{
  public B()
  {

  }
}

In the constructor of class B, if I try this._table, it doesn't compile? Why does it not?

But to get it to work, I have to add using System.Data; and everything works fine.

Why does .NET not do this for me? So that when I try to access the protected member, it knows that its a System.Data.DataTable?

forgive me if the classes are 100% correct...

From stackoverflow
  • Other than the semi-colon missing after the declaration of _table, it's fine. On the other hand, I personally avoid having fields with an access modifier of anything other than private.

    James Curran : "anything other than public" or "anything other than private" ?
    Jon Skeet : Oops, thanks James. Fixed :)
    Miles : just fixed that dang semi-colon... no dang intelli-sense here to fix it for me.. hehe
    Jay Bazuzi : I see no problem with using internal fields. YAGNI.
    Jon Skeet : Jay: I think we'll have to agree to differ. I prefer not to let even other classes within the same assembly violate encapsulation. I regard fields as a matter of implementation, not API.
    Wedge : I've come around on the fields vs. properties debate. With C# 3's syntax, properties are pretty much free, and the ability to easily make them publicly read-only seals the deal.
  • This is not a language issue - if anything, you could call it an IDE issue, for not adding the using statement when creating the new class. Even then, the IDE does not know you will be accessing this member, and I prefer to keep my "usings" as minimal as possible. In any case, the fact that B extends A does not tell the compiler anything about which namespaces it must search for the types referenced in B.

    Also, I would strongly suggest you change your access of the _table member to use a getter property.

    Jon Skeet : You don't need the using directive anyway, necessarily. For instance, you could write: Console.WriteLine(_table); with no issues.
    Jon Skeet : (Oh, and the linker doesn't care about namespaces. It cares about assemblies.)
    harley.333 : Console.WriteLine expects an Object, so it does not need the _table's Type.
    Chris Marasti-Georg : Thanks for the clarification Jon
    Jon Skeet : @harley: Exactly. There's nothing in the OP's question suggesting that he needed using System.Data.
  • Hmm

    Is this exact code? I don't see a semi-colon after your declaration of _table...

    Miles : no, this isn't the exact code, thats what i mentioned up in the original message
  • Are the classes in the same assembly? I tried your sample with the classes in the same assembly and it compiled fine.

  • It should work. I just tried it and it does work.

    Check if both classes are in the same namespace. If they are not, don't forget to include the namespace of class A with the using keyword.

    Check if both classes are in the same assembly. If they are not, don't forget to include a reference to the assembly of class A in the assembly of class B.

  • I agree with ya'll that they should be using "getters/setters" and just set the _table to private.

    I was just curious to why the .Net language wouldn't even let it compile....

    Jon Skeet : Given that it compiles when we try the code you've given, it's hard to say. What was the error message?
  • Actually I don't think the compiler even looks at _table, as soon as it sees DataTable and sees that it's an undefined type it will skip forward to the next line that looks syntatically correct. I think even if you had some junk variable after DataTable in class B you would still get the same error.

  • Shouldn't we be fully qualifing our types in a class anyway? It was the mantra driven into my head while learning c++ anwyay.

    Mark Ingram : Nope, not unless you like reading really wide lines of code. And after you've seen your 1000th System.Windows.Form.* namespace, it begins to drag a little...
    : Thanks... While coding I use namespaces but for release builds I fully qulaify everything. The idea as I was taught was to remove any possible ambiguity...
  • I'm agreeing with ya'll now.

    I thought I'd post the question because I believed my coworker knew that he was talking about. I tried the following and had now problems:

    using System.Data;
    
    namespace WindowsApplication1
    {
        public class classA
        {
            protected DataTable _table;
    
            public classA()
            {
    
            }
        }
    }
    

    next file:

    namespace WindowsApplication1
    {
        public class classB : classA
        {
            public classB()
            {
                this._table = new System.Data.DataTable();
            }
        }
    }
    

    and that compiled just fine. I thought there was going to be a problem with a linkage between all the .Net namespaces but there's not.

    Thanks for all the comments/answers.

What are the traits that you look for in a software developer?

Specifically, what are the best indicators to forecast if someone will be a great developer, and also, someone that you would want to work with?

Examples:

  • education
  • breadth of technical knowledge
  • depth of knowledge in a particular domain
  • interpersonal skills
  • work on open source projects
  • choice of tools, operating systems, and languages
  • taste in music
  • etc

Please: Only one trait per response, so they can be voted up or down.


This question is intentionally similar to a question on the traits of software development managers. Since many software managers are software developers who got promoted, I think it will be interested to see if the traits line up.


Edit:

For the record, this was not an attempt to gain any reputation, badges or bonus bucks. With help from thesmallprint (that's a username, not a legal reference), I just learned about the "community wiki" feature, and happily turned it on. Now you can feel free to vote and comment with the reassurance that this question will not improve my reputation, or help me get the coveted Almighty Ruler badge, which I could then use to crush your dreams/soul.

My experiences with this site have been very promising -- the caliber of the questions and answers has been impressive. So, if you find this question too subjective, I offer my apologies. I have had this question (and the other like it) rolling around in my head for a while now, and I assumed that other developers would consider it interesting.

If you like this question...please leave a comment or vote.

On the other hand, if you still hate me and my question...please shake your fist in the air, then vote me down and leave discouraging comment. Then you can go to bed content with the knowledge that you've made the world a better place by making me feel dumb.

From stackoverflow
  • Professional integrity: someone who can be honestly self-critical can always re-train themselves if they realize that they need a new skill. They can recognize that their design has flaws and aren't afraid to admit it. They can stand up for their design when it's the criticism that has flaws. They can remember that this is all a job and that we need to get it done so that we can get back to our lives.

    On the other hand, working without integrity is horrible. You can never be sure that this guy remembers that we're all on the same team.

  • Curiosity; a desire to find out how something works, which is, I think, a desirable trait for any engineer.

  • The best software developers to work with and have work for you are those who are passionate about software development, and are always eager and willing to improve themselves and learn new skills. These are the types of developers who can excel on just about any project.

  • The single quality that should be same no matter what profession is that they reduce the number of existing problems at the end of the day regardless of what they do.

  • Persistence:

    Willing to keep at it until the "right" solution is found.

  • Something I'd like to see in someone I'd be working with is patience. As slow as it may feel during planning stages, the time it takes to get things clearly laid out is remade in spades later on.

  • Someone who knows how to use Google before asking for help.

  • Pragmatism.

    Most of the responses so far are great in moderation, but can be very difficult to work with if taken to extremes.

    In cases where you're writing software in a company environment these other attributes all need to be present, but need to be tempered by a sense of pragmatism about the end goal of writing this software - to fulfill a set of requirements to meet a business need in a timely fashion.

  • Passion and humility.

    Passion means you care about your code and want to continuously improve yourself. Humility allows you to help other people improve and allow other people to help you improve.

    • lazyness, i.e. don't repeat yourself, don't reinvent the wheel
    • paranoia, i.e. defensive coding, expect the unexpected
    • neophilia, i.e. don't stay where you are now, keep learning, try new things
    oxbow_lakes : Ooh, almost there!
  • The one that has jumped to the top of my list: Critical thinking ability -- how to take a problem, decompose it, ask relevant questions, suggest solutions or paths to solutions. Show me how you THINK, how you approach tasks.

  • Good Googling skills.

  • Communication skills - How well can you talk and write? A few questions for what I'm thinking but not directly asking:

    • Can you translate things from technical to non-technical easily?
    • Can you articulate why something should and shouldn't be done?
    • If I don't understand what you just told me, what do you do to try to help me "get it"?
    • Do you try to use proper English or is slang quite common in your vocabulary,e.g. "Word to mother, Holmes."
    • Do you try to use very specific words or does your vocabulary tend to be rather small? Do you use big words to try to sound smart or are you really aware of the scale of the terms in your diction?
    • If you find a bug, what steps do you take so that it can be recorded in an efficient way for developers to fix it? Do you just say, "It's broken," or do you give a list of steps to reproduce the error in a verifiable manner?

    This is in addition to thinking about how well does someone use their voice in terms of becoming louder for some points, softer on others, changes in tone or pitch and other things that can make talking fun.

Interface doesn't accept inherited member (OO question)

I feel like a fool, but here goes:

public interface IHasErrorController{
  ErrorController ErrorController { get; set; }
}

public class DSErrorController: ErrorController{yadi yadi ya}

public class DSWebsiteController : Controller, IHasErrorController{
    public DSErrorController ErrorController { get; set; }
}

This gives me an error saying DSWebsiteController.ErrorController cannot implement IHasErrorController despite DSErrorController being inheritted from ErrorController.

Also, suggestions for a better naming so that the type ErrorController and the field Errorcontroller don't look the same are welcome (naming is hard).

From stackoverflow
  • C# (at the moment) has very little [co|contra]variance support; as such, the interface implementation must be an exact match, including the return type. To keep your concreate type on the class API, I would implement the interface explicitly - i.e. add:

    ErrorController IHasErrorControlloer.ErrorController {
      get {return this.ErrorController;}
      set {this.ErrorController = (DSErrorController)value;}
    }
    

    Alternatively, simply change the type of the property to ErrorController - this may (or may not) give what you need.

    borisCallens : With your code sollution you mean to put a cast in your setter, right? Just making sure I understand it all right.
    Marc Gravell : My bad; have added.
  • This is true; that is not allowed. (The proper name is "Covariant return types")

    Note that DSWebsiteController.ErrorController can physically return a DSErrorController object; it's just that the property's return value must be defined as ErrorController.

  • Ok, so it's not me not knowing my OO principles then. Is this something that is planned to be included?

    I find it strange that I never came across this since this is a rather usefull functionality in my eyes. Or are there better ways to solve the problem at hand?

    Thanks Marc, now I finally understand what this "implement interface explicitly" is all about :)

    Marc Gravell : It is certainly something that the C# team talks about occasionally, but who knows what we'll get when. It isn't a simple area, but arguably the compiler (with a different spec!) could have done some inference for us in the above example (i.e. it could have done what I did).
    Marc Gravell : Scratch my comment about inference; the cast I forgot means that this wouldn't be a safe example - but I have /seen/ perfectly safe examples that would qualify.

What options are available for connecting to a Microsoft SQL Server database from an Oracle database?

At the moment I pull data from remote MS SQL Server databases using custom-built JDBC connectors. This works fine but doesn't feel like the way to do it.

I feel I should be able to put a JDBC connection string into tnsnames on the server and have it "just work". I've looked around a little for this functionality but it doesn't seem to be there.

In this way I could connect to pretty much any database just using a database link.

Have I missed something?

From stackoverflow
  • Generic Connectivity is what you are after, it will let you setup a remote database link against MS SQL Server, so you can do queries like

    select * from mytable@my_ms_sql_server;
    

    I've only used it in Oracle 9i against mysql, and found, that in our cases, it didn't work very well, as it ended up using up MASSIVE amounts of ram, we still use it, but now just use it for syncing to a local table rather than doing 'live' queries against it. BUT, it might be completely different against MS SQL Server, and in 10g/11g

  • Another product to look at is Oracle Gateways.

    Have a look at:

    http://www.oracle.com/technology/documentation/gateways10g.html

  • It looks like the two options are Generic Connectivity and Oracle Gateways but I'm surprised that's all there is. Generic Connectivity comes with the database license and Oracle Gateways is an add-on. For Generic Connectivity, if you're running on Linux (like me) you need to get hold of an ODBC driver as it isn't bundled with the database.

    However... with Oracle being such keen Java fans, and with a JVM built-in to the database I'd have thought a JDBC-based linking technology would have been a no-brainer. It seems a natural extension to have a JDBC connection string in TNSNAMES and everything would "just work".

    Anyone any ideas why this isn't available?

    Nick Pierpoint : That's a thought - might do that. Thanks·
    Nick Pierpoint : I did end up asking this as a new question. It didn't go down well. Never mind. :-) http://stackoverflow.com/questions/198703/why-isnt-querying-a-jdbc-compliant-database-from-oracle-as-easy-as-pie

How do I get the terminal within GVim to react to mouse scrolls?

I'm on a Hardy Heron Ubuntu build, BTW.

From stackoverflow
  • Hate to give this answer, because it isn't very helpful, but it works fine for me (scroll wheel in gvim on ubuntu hardy).

    But maybe I can suggest some things that help debug the issue:

    1. Confirm you are running "gvim" and trying to scroll the new window that comes up (i.e. you are not running vim in an xterm and trying to scroll that with the mouse)
    2. Confirm the scroll wheel works in other apps. Use "xev" to make sure the X server is seeing the scroll events if you're unsure.

    Hope that helps.

    : The scroll wheel works fine for the rest of the Gvim's modes. The only place where the problem appears is when the console's ":!" output exceeds the window size. (It works the way it's supposed to when I'm under gnome-terminal and xterm, though.)
  • Try:

    :set mouse=a

    ":help mouse" says

    Enable the use of the mouse.  Only works for certain terminals
    (xterm, MS-DOS, Win32 |win32-mouse|, qnx pterm, and Linux console
    with gpm).  For using the mouse in the GUI, see |gui-mouse|.
    The mouse can be enabled for different modes:
     n Normal mode
     v Visual mode
     i Insert mode
     c Command-line mode
     h all previous modes when editing a help file
     a all previous modes
     r for |hit-enter| and |more-prompt| prompt
     A auto-select in Visual mode
    Normally you would enable the mouse in all four modes with: >
     :set mouse=a
    When the mouse is not enabled, the GUI will still use the mouse for
    modeless selection.  This doesn't move the text cursor.