Thursday, March 24, 2011

Should object properties be filled in the constructor

I'm designing a new application and I'm undecided if I should fill my object properties on the constructor

Public Sub New(UserId as integer)
    ' get database values
    dr = DataReader
    Me.FirstName = dr.fields(0)
    Me.LastName = dr.fields(1)
End Sub

Or create a factory with a method for each object type?

Public Function getUser(UserId as integer) as User
    Dim myUser as new User
    ' get database values
    dr = DataReader
    myUser.FirstName = dr.fields(0)
    myUser.LastName = dr.fields(1)
    return myUser
End Function

I realize that the code is rough, but I'm hoping it's enough to get my point across. I've see both implemented and not sure what the long term pros and cons are.

Specifically, I'm using VB.NET, if it matters.

From stackoverflow
  • I like types to be immutable where that doesn't create other problems. For a "person" type it may not be suitable, but it's worth considering. You should also try to construct objects so that after the constructor has been called, the object is in a valid state.

    On the other hand, you should try to avoid doing too much work in the constructor itself - this is where static factory methods tend to be nice, as they can do significant work to grab all the data needed to construct the object, then pass it on to a simple constructor to create a complete, valid and potentially immutable object.

  • It really depends on the language because some languages cannot guarantee the state of the object until the constructor and all base constructors have finished executing.

    I find it best to populate whatever members you need and then call methods to do the rest of the work. This tends to make the code more readable as you won't have lots of code in your constructors.

  • My opinion:

    A constructor creates an object. The constructor of a User class should create a new user.

    Static member functions like your getUser retrieve an object which already exists.

    I would use the latter form.

    flq : I agree. That way there is also no need to reference a DataReader in your User class. That way you may be able to play with your User object in other secnarios and populate its values simpley by setting them.
    1. You are instantiating the userhandler-object and using that to get different users, and let you work with all users. Have a GetUser-function and nothing in the constructor.

    2. You are instantiationg the userobject and working only with THE user, have the constructor handeling witch user to work with.

    My 5 cents.

  • I would use a Factory-Pattern and make the constructor private/protected and make a static NewObject() method. The NewObject-method can then call the appropriate constructor. The pro on this is that if you need to change the behaviour of the Object during runtime you can plug-in (override) the NewObject-method and have your own NewObject-method "mixed in". The downside of this is that it can get very complex very fast - especially if you're debugging it.

  • An object should be 100% ready for use when it's constructed. A default constructor should have sensible, non-null default values for all references.

    If you find that your constructor has "too much" code, perhaps it's time to consider refactoring that object.

ASP.NET Web App Distribution

What is the simplest way to distribute an web application? I tried to look at some of the open source projects out there to see how they distribute their apps and how they do updates and they seem rather complicated to me (not for myself to perform but for non-technical users). A lot of them entail backing up the entire installed project, deleting specific folders and save parts of their web.config. I am hoping to find a solution that will make the update process specifically as simple as possible.


From stackoverflow
  • Do you mean in terms of breaking up the functionality into tiers that could be handled on separate machines, e.g. having 3 servers for a 3-tier architecture where one is the DB server, one handles middleware and the other handles the requests in ASP.Net? Another point here would be in going from a web server to multiple web servers in terms of scaling up.

    Or are you referring to deployment?

  • CommunityServer provides a setup msi that will create a virutal directory, generate the SQL database and populate it with default data. Updating for point releases though is still a manual process involving an update.sql file and having everyone download then merge binary and static file changes.

    They probably could have created an update msi too, but because so many people customize CommunityServer, it is probably better to let people merge changes themselves.

  • I am working on a project with a similar requirement now. We decided to use WiX to create an installer that can be run on the server or machine where the site is installed. WiX is incredibly powerful, but takes a bit to get the hang of.

    There are plenty of other open source, and paid installer technologies as well. Here is a post with some info on a few.

  • It's a web application, man. Serve it publicly, require registration, and move on. Isn't that the point of the web application?

Intermittent InavlidCastException in a UserControl.InitializeComponent()

Thanks in advance for any help with this. It is driving me nuts. Here is the setup:

I have a Silverlight Control Library "Controls", in which I have a customer control defined for presenting dialogs:

public class Dialog : ContentControl
    public Dialog()
        : base()
        DefaultStyleKey = typeof(Dialog);

<...normal custom control stuff...>

also the default style is in generic.xaml:

  <Style TargetType="src_general:Dialog">
        <Setter Property="Padding" Value="25"/>
        <Setter Property="Template">
                <ControlTemplate TargetType="src_general:Dialog">
                    <Grid x:Name="RootElement" >
                            <vsm:VisualStateGroup x:Name="DiakogStyleStates">
                                <vsm:VisualState x:Name="OkCancel">
                                <vsm:VisualState x:Name="OkOnly">
                                        <ObjectAnimationUsingKeyFrames Duration="0:0:0" Storyboard.TargetName="CancelButton" Storyboard.TargetProperty="Visibility" >
                                            <DiscreteObjectKeyFrame KeyTime="0:0:0" >
                                <vsm:VisualState x:Name="CancelOnly">
                                        <ObjectAnimationUsingKeyFrames Duration="0:0:0" Storyboard.TargetName="OkButton" Storyboard.TargetProperty="Visibility" >
                                            <DiscreteObjectKeyFrame KeyTime="0:0:0" >
                                <vsm:VisualState x:Name="None">
                                        <ObjectAnimationUsingKeyFrames Duration="0:0:0" Storyboard.TargetName="CancelButton" Storyboard.TargetProperty="Visibility" >
                                            <DiscreteObjectKeyFrame KeyTime="0:0:0" >

                                        <ObjectAnimationUsingKeyFrames Duration="0:0:0" Storyboard.TargetName="OkButton" Storyboard.TargetProperty="Visibility" >
                                            <DiscreteObjectKeyFrame KeyTime="0:0:0" >

                        <Popup x:Name="DialogPopup">
                            <src_general:WindowFrame x:Name="Frame">
                                <Grid >
                                        <RowDefinition Height="*" />
                                        <RowDefinition Height="Auto" />

                                    <ContentPresenter Grid.Row="0" x:Name="ContentPresenter" Margin="{TemplateBinding Padding}"/>

                                    <!--Action Buttons-->
                                    <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right" Margin="15">
                                        <src_general:GlassButton x:Name="CancelButton" Content="Cancel" Margin="2"/>
                                        <src_general:GlassButton x:Name="OkButton" Content="Ok" Margin="2"/>


I use this dialog in a lot of places with no problem. However, in one application, nested about 3-4 usercontrols from the RootVisual, I use it the following way:

<general:Dialog x:Name="AddUpdateDialog" DialogStyle="OkCancel" Title="Add/Update Connection" Closed="AddUpdateDialog_Closed" ValidationGroup="AddConnection">
            <Grid Width="300">
                    <RowDefinition Height="Auto"/>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="10"/>
                    <ColumnDefinition Width="*"/>

                <TextBlock Grid.Row="0" Grid.Column="0" Text="Name:" Style="{StaticResource LabelText}"/>
                <TextBox Grid.Row="0" Grid.Column="2" Text="{Binding Name, Mode=TwoWay}" Style="{StaticResource TextBoxInput}" MaxLength="49">
                        <val:RequiredValidator ManagerName="AddConnection" ErrorMessage="Name is required."/>

When I run this app I intermittently (about every 5-10 starts get the following exception: "Unable to cast object of type 'System.Windows.Controls.ContentControl' to type ''." that occurs in the InitializeComponent() for the parent UserControl of the above XAML. To be sepcific, it occurs right here:

           this.AddUpdateDialog = (("AddUpdateDialog")));

When I put a breakpoint there, most of the time the FindName returns a Dialog typed object, but sometimes, it returns a ContentControl (the base for Dialog) and it fails. The XAML has not changed. It is static...Since the exception is intermittent and occurs within generated code I am at a loss.

I have tried: 1) Moved all of the content for the Dialog into a separate UserControl - only seemed to make problem worse 2) Comment out parts and see when it works...well, if I comment out the TextBox completely, it no longer fails. Everything else (including the custom validation attached property) seems to have no impact. 2a) Thinking it may have something to do with the TwoWay binding to the TextBox, I removed the binding. Still fail.

UPDATE: So given 2) above I left the Textbox commented out decided to move on to other things and come back to this with hopes that something will reveal itself to me. Unfortunately, it seems to also fail with the textbox out, just less frequently.

In addition, I have this control in the exact same configuration in another usercontrol in the same app (and at the same level in the VisualTree) and it does not fail at all. So I literally copied and pasted the failing XAML into the Main.xaml (my root visual) and of course, it does not fail there either. Assuming that the the XAML is loaded in sequence (top to bottom) the failing control is likely one of the last ones loaded. My only hypothesis now is that there is some timing thing that is happening whereby as Iam still loading the visual tree, I start to get *Completed events from the loading of the data via WCF service and that these trigger a layout before the visual tree is fully loaded which causes some ill side effects... I will test this.

The problem is that it does NOT fail every time. It blows up about 20% of the time. When it works, everything works even this dialog???

This problem is related if not the same problem: When I "fix" the invalidcast by commenting out needed functionality, I will far less frequently but intermittently get this invalid attribute (when the attribute/property is in fact there).

Help please.

From stackoverflow
  • After much, much research and frustration, I believe it to be related to this:

    The Loaded event in Silverlight does not match the definition of (a) what it is in WPF and consequently (b) the definition that they pasted into the Silverlight documentation from WPF


    I have modified some code based on the above and now it does not seem to fail. I wish I could tell you exactly why it did what did and why what I did fixed it (or at least masked it again??), but I can't. Maybe someone else will encounter this and can figure it out.

    Here is what I was doing and what I changed:

    The Textbox above makes use of an Attached Property for a Validator (like the ASP.NET validators and similar to the ones in the Silverlight Toolkit). When a Validator (base class for RequireValidator) is attached to a control, it links to the control to provide validation as an attached behavior. The trick is that it then tries to Validate() the current control. For a RequiredValidator on a TextBox control it calls string.IsNullOrEmpty() for the Text property on the linkedControl. All of this works fine as these are just properties on the TextBox Control. However, just after that, the validator needs to somehow tell the control to display the error indicator and any error message. I do this through providing a custom Style that includes two new VisualStates ("ValidInput" & "InvalidInput") in their own VisualStateGroup ("ValidationStates") and that one of the Style's Elements is a Control that supports and interface called IValidationNotificationControl.

    Ok, enough background. From the documentation, I knew that I could only access the elements of the TextBox Style (the new visualStates and the notification icon) AFTER the template had been applied so I hooked into the Loaded event for the linkelement for the validator and called Validate() there for the first time. Well, someone at MS saved about 15 minutes by copying an pasting the Loaded Event description from WPF and that cost me about 3-4 days of heartache. Turns out that there is no guarantee that the template is applied then in Loaded Event in silverlight. So, I simply added a call to ApplyTemplate() in the Loaded event handler for the linkedelement and the failure went away.

    My guess is that the error was intermittent because the Layout (and therefore the application of the Template) occurs asynchronously and sometimes it was there when I hit the Loaded Event and sometimes it was not. But I still think that it is a Silverlight Bug as to where the error manifested itself and may even point to a security hole (if, but some action, somewhere else in the code, I can cause the XAML Parser to return a type different than what teh actual XAMl indicates...). Oh seems to be working now. Maybe this will help someone else.

  • Maybe this helps someone too: take a look at my answer in another thread:

What is the best way to do a simple Parent-Child drop down in pure Javascript

I need to do a quick and dirty 'Country' --> 'State' drop down relationship on a web form. I only am concerned with the states, provinces, and territories for USA and Canada, and this will be a relatively lightly used form, so a pure javascript solution is probably ideal.

From stackoverflow
  • Create a JSON array:

    array = [ { name: "United States", states: [...] }, { ... } ];

    When the value of the dropdown changes, fill in the other drop down with the contents of the particular element from the array.

Application access server load

Hello. I have developed an application in PHP + Javascript. I'm using MySQL as database support. Every account for this app will come with a subdomain... so the client Stardust would have I want to put the application files in a folder outside public_html and link every account from every subdomain created to this files folder through a config file that would stay in each subdomain. Just for specifying the database infos. My questions is: Would I have more server load if I put every customer to access files from the same folder than I would have if I put the files in every subdomain, separately for every client ? Would 500 customers accessing the files in the same time all from one location be the same with 500 customers accessing files separately from its own folder ?

Thank you.

From stackoverflow
  • The operating system will cache files, so having 500 copies means a lot more caching and a lot more disk IO than one copy. You may want to simply have a "master" application that understands subdomains (i.e. user1 is associated with subdomain1) and use apache redirects/etc to send all the requests to the master application/etc.

Handling RSS Tags with NSXMLParser for iPhone

I've found the following code for parsing through RSS but it does not seem to allow for nested elements:

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{     
    NSLog(@"ended element: %@", elementName);
    if ([elementName isEqualToString:@"item"]) {
     // save values to an item, then store that item into the array...
     [item setObject:currentTitle forKey:@"title"];
     [item setObject:currentLink forKey:@"link"];
     [item setObject:currentSummary forKey:@"summary"];
     [item setObject:currentDate forKey:@"date"];
     [item setObject:currentImage forKey:@"media:thumbnail"];

The RSS to used is:

    <item><title>Knife robberies and burglaries up</title>
<description>The number of robberies carried out at knife-point has increased sharply and burglaries are also up, latest crime figures indicate</description>
<guid isPermaLink="false"></guid>
<pubDate>Thu, 22 Jan 2009 13:02:03 GMT</pubDate><category>UK</category>
<media:thumbnail width="66" height="49" url=""/>

I need to extract the "url" element from the "media" tag.

Thanks Martin

From stackoverflow
  • You need to get the attributes (including the URL) when the element starts:

  • As August pointed out, you will have to use didStartElement to get to the attributes of a tag. The attributes are returned as a dictionary with the attribute names as the keys and attribute values as the values.

  • August Coud you Show some example code to store url ? thanks

  • I've just released an open source RSS/Atom Parser for iPhone and hopefully it might be of some use.

    I'd love to hear your thoughts on it too!

  • Hi! Im having the same problem: parsing the image... Can anybody help? Thanks!

How to validate this scenario in ASP.NET MVC?

First, a little bit of context (cause I know you all love it!):

I have a model called Note. It has a field called Type which, in the database, is an integer value that designates which type of object this note belongs to (1 = Customer, 2 = Sales Lead, etc). A second field called Source designates the ID of the specific object that this note belongs to.

For example, if I wanted to add a note to Customer #34, I would set Type to 1 and Source to 34.

To help make things a little more readable, I have an Enum called DataObjectType that contains a mapping for each of the possible Type integer values to a friendly name. So, for example, DataObjectType.Customer is the same as a value of 1 in the Type field.

Next, I have a custom route:


and two controller actions to handle the creation of a new note:

public ActionResult New(DataObjectType type, int id) {
    Note note = new Note { Type = type, Source = id };
    return View(note);

public ActionResult Create(Note note) {
    // This is just an example
    return View("New", note);

First of all, I need to make sure that the value supplied to the {type} route value is valid for the DataObjectType enum. Can this be done with a route constraint? At the moment, the type argument of New() will accept any integer, whether it exists in DataObjectType or not.

Second, I need to make sure that the object the user is trying to add the note to actually exists in the database before showing the New Note form at all. I could do this in the New() method easily, but there may come a time when a user posts the data directly to Create() without ever visiting New(). In such a case, I also need to verify that the object exists in the Create() method. What's the best way to do this in both methods without duplicating code?

From stackoverflow
  • When setting up your routes, there's a parameter you can use to specify constraints (done via Regex). You could use this to restrict the id there, but you would have to create a separate route for this scenario because you wouldn't want all "id"s to be filtered on that rule.

    Alternatively, you could just stick this check at the beginning of your controller action.

    As for ensuring that the note already exists in the db, I can't see any way around sticking a check at the beginning of the Create action.

  • You are correct that both the New and the Create actions need to ensure that they have a valid model passed to them. The correct place to do this is in a model binder. The model binder should add a model state error if an invalid object (or Id) is passed. New and Create can likely use the same model binder(s).

    Don't confuse route constraints with user input validation. Route constraints simply help the routing system find the appropriate route when you don't specify the route yourself (i.e., when you use Html.ActionLink instead of RouteLink). If you use named routes, and you should, then the constraint is not needed to find the appropriate route, because you have specified the route directly. Route constraints are intended to prevent a certain route from being selected for actions it is not designed to handle, and are not the place to validate user input.

    The feature you are asking for is a kind of user input validation, even though user input in question happens to be in the URL. If you are going to go beyond this simple, single case, you might want to look into using a validation framework, as this will make other types of validation much simpler. Here is one which looks interesting to me.

Get current date and time in PHP

What PHP function file can return the current date/time?

From stackoverflow
  • You can either use the $_SERVER['REQUEST_TIME'] variable (available since PHP 5.1.0) or the time() function to get the current Unix timestamp.

  • PHP's time() returns a current unix timestamp. With this, you can use the date() function to format it to your needs.

    $date = date('Format String', time());

    As Paolo mentioned in the comments, the second argument is redundant. The following snippet is equivalent to the one above:

    $date = date('Format String');
    Paolo Bergantino : the 2nd argument of the date function is assumed to be time() if left empty.
  • You can use both the $_SERVER['REQUEST_TIME'] variable or the time()function. Both of these return a Unix timestamp.

    Most of the time these two solutions will yield the exact same Unix Timestamp. The difference between these is that $_SERVER['REQUEST_TIME'] returns the time stamp of the most recent server request and time() returns the current time. This may create minor differences in accuracy depending on your application, but for most cases both of these solutions should suffice.

    Based on your example code above, you are going to want to format this information once you obtain the Unix Timestamp. An unformatted Unix timestamp looks like this...

    Unix Timestamp: 1232659628

    So in order to get something that will work, you can use the date() function to format it.

    A good reference for ways to use the date() function is located in the PHP Manual Pages, here...

    As an example, the following code returns a date that looks like this -

    01/22/2009 04:35:00 pm

    echo date("m/d/Y h:i:s a", time());
  • $date = date('m/d/Y h:i:s a', time());

    Thank you... works, but how also to know if it's EST, PST?

    Gumbo : Look into the manual:
    TravisO : The date function is the time of your server, either check it, or temporarily set it /w PHP before you run date.
  • The time would go by your server time. An easy workaround for this is to manually set the timezone before the date() or time() functions are called to.

    I'm in Melbourne, Australia so I have something like this:


    Or another example is LA - US:


    You can also see what timezone the server is currently in via:


    So something like:

    $timezone = date_default_timezone_get();
    echo "The current server timezone is: " . $timezone;

    So the short answer for your question would be:

    // Change the line below to your timezone!
    $date = date('m/d/Y h:i:s a', time());

    Then all the times would be to the timezone you just set :)

    too much php : The call to time() is redundant, date() will automatically use the current time.
  • how display time and date for whenever file was made??? pls give me answer..

When is InputStream available when uploading a large file?

When is PostedFile.InputStream available when uploading a large file?

I'd like to pass a Stream to another process and I'm hoping that if a large file was being uploaded that I can pass the Stream straight to that new process w/o writing to the file system. Since the process and/or upload could take a while, I'm wondering if I can start reading the InputStream immediately or whether I have to wait for the whole file to be transferred to the server before it can be processed.

I guess a more general question is - what's the lifecycle of a POST request when file upload is involved?

From stackoverflow
  • The PostedFile.InputStream isn't available until the entire file has been uploaded. IIS6 caches the file in memory while IIS7 now caches the file to disk before handing off the input stream to your method.

    You can get a HttpModule such as NeatUpload which allows you access to the bits while they're uploading.

How to automatically generate N "distinct" colors?

I wrote the two methods below to automatically select N distinct colors. It works by defining a piecewise linear function on the RGB cube. The benefit of this is you can also get a progressive scale if that's what you want, but when N gets large the colors can start to look similar. I can also imagine evenly subdividing the RGB cube into a lattice and then drawing points. Does anyone know any other methods? I'm ruling out defining a list and then just cycling through it. I should also say I don't generally care if they clash or don't look nice, they just have to be visually distinct.

public static List<Color> pick(int num) {
 List<Color> colors = new ArrayList<Color>();
 if (num < 2)
  return colors;
 float dx = 1.0f / (float) (num - 1);
 for (int i = 0; i < num; i++) {
  colors.add(get(i * dx));
 return colors;

public static Color get(float x) {
 float r = 0.0f;
 float g = 0.0f;
 float b = 1.0f;
 if (x >= 0.0f && x < 0.2f) {
  x = x / 0.2f;
  r = 0.0f;
  g = x;
  b = 1.0f;
 } else if (x >= 0.2f && x < 0.4f) {
  x = (x - 0.2f) / 0.2f;
  r = 0.0f;
  g = 1.0f;
  b = 1.0f - x;
 } else if (x >= 0.4f && x < 0.6f) {
  x = (x - 0.4f) / 0.2f;
  r = x;
  g = 1.0f;
  b = 0.0f;
 } else if (x >= 0.6f && x < 0.8f) {
  x = (x - 0.6f) / 0.2f;
  r = 1.0f;
  g = 1.0f - x;
  b = 0.0f;
 } else if (x >= 0.8f && x <= 1.0f) {
  x = (x - 0.8f) / 0.2f;
  r = 1.0f;
  g = 0.0f;
  b = x;
 return new Color(r, g, b);
From stackoverflow
  • If N is big enough, you're going to get some similar-looking colors. There's only so many of them in the world.

    Why not just evenly distribute them through the spectrum, like so:

    IEnumerable<Color> CreateUniqueColors(int nColors)
        int subdivision = (int)Math.Floor(Math.Pow(nColors, 1/3d));
        for(int r = 0; r < 255; r += subdivision)
            for(int g = 0; g < 255; g += subdivision)
                for(int b = 0; b < 255; b += subdivision)
                    yield return Color.FromArgb(r, g, b);

    If you want to mix up the sequence so that similar colors aren't next to each other, you could maybe shuffle the resulting list.

    Am I underthinking this?

  • You can use the HSL color model to create your colors.

    If all you want is differing hues (likely), and slight variations on lightness or saturation, you can distribute the hues like so:

    // assumes hue [0, 360), saturation [0, 100), lightness [0, 100)
    for(i = 0; i < 360; i += 360 / num_colors) {
        HSLColor c;
        c.hue = i;
        c.saturation = 90 + randf() * 10;
        c.lightness = 50 + randf() * 10;
    mquander : This technique is smart. I bet it'll get more aesthetic results than mine.
  • Here's an idea. Imagine an HSV cylinder

    Define the upper and lower limits you want for the Brightness and Saturation. This defines a square cross section ring within the space.

    Now, scatter N points randomly within this space.

    Then apply an iterative repulsion algorithm on them, either for a fixed number of iterations, or until the points stabilise.

    Now you should have N points representing N colours that are about as different as possible within the colour space you're interested in.


  • Here's a solution to managed your "distinct" issue, which is entirely overblown:

    Create a unit sphere and drop points on it with repelling charges. Run a particle system until they no longer move (or the delta is "small enough"). At this point, each of the points are as far away from each other as possible. Convert (x, y, z) to rgb.

    I mention it because for certain classes of problems, this type of solution can work better than brute force.

    I originally saw this approach here for tesselating a sphere.

    Again, the most obvious solutions of traversing HSL space or RGB space will probably work just fine.

    Rocketmagnet : That's a good idea, but it probably makes sense to use a cube, rather than a sphere.

What is the best way to handle style tags when loading HTML with AJAX in IE 6 or 7?

Our AJAX framework works such that it sends back a snippet of HTML that might contain a tag. We then take that snippet of HTML and set it to be the innerHTML of an element. In IE 6/7 it appears to ignore the tags and so the returned HTML isn't styled properly.

I'm wondering if other people have run into similar problems, and if so, how they've dealt with them. I know I could use a javascript library (we use YUI) to dynamically get external style sheets, so I could convert this to an external style sheet. Just wondering if there are other ways to fix this.

From stackoverflow
  • Of course the best method is a pure DOM solution, ie use document.createElement to generate all the elements returned by the server.

    However, there is (of course) an IE hack to work around some of the problems presented by innertHTML. Instead of sticking the response straight into the DOM, first create an element, append its innerHTML, then attach it to the DOM.

    function responseHandler(response) {
        var div = document.createElement('div');
        div.innertHTML = response.responseText
    Mike Robinson : Definitely the most reliable way, especially when it comes to further manipulation. IE 6/7 don't do innerHTML on tables at all. Also, innertHTML? Is that what Yahoo uses?
  • Inline style tags should be recognized. A styelsheet block will not, as they are loaded at the page's initial render time.

    You can dynamically add classes you the existing stylesheet, but you'll have to parse your HTML fragment to grab what's there and do it in script.

    see: Totally Pwn CSS with Javascript

How to programmaticaly import Java class

Is there a way in Java to programmatically import a class given its full name as a String (i.e. like "com.mydummypackage.MyClass")?

From stackoverflow
  • If by "import" you mean "load a Class object so you can run reflection methods," then use:

    Class<?> clazz = Class.forName( "com.mypackage.MyClass" );

    (The reason we readers were confused by your word "import" is that typically this refers to the import keyword used near the top of Java class files to tell the compiler how to expand class names, e.g. import java.util.*;).

  • The Java Documentation is a great source of knowledge for stuff like this, I suggest you read up on the Class Object Documentation which can be found here:

    As mentioned in Jason Cohen's answer you can load a Class object using the following line of code and then to create an instance of that class you would execute the newInstance method of the Class object like so:

    Class<?> clazz = Class.forName( "com.mypackage.MyClass" );
    Object o = clazz.newInstance();
  • Don't confuse "import" with class loading.

    The import statement doesn't load anything. All it does is save you from having to type out the fully resolved class name. If you import, you can refer to class Baz in your code instead of having to spell it out. That's all import means.

    xelurg : aaaah... ok, I see now. Thanks a lot, this is an important bit that I've missed when reading Java 101 I guess...

Should I share the Entity-Framework context or create a new context for each operation?

I'm not that clear on the best-practice concerning the use and re-use of the entity-framework Context.

My question is, should I try to create 1 context and re-use it many times for different queries or should I create a new context for each query?

For example if I have a form with 10 charts all with data queried from the same tables, should the 10 queries be from the one context or 10 different contexts?

From a code encapsulation point-of-view I'd prefer to create 10 new contexts, is this a good idea and is it scalable?

From stackoverflow
  • IMHO - i could be wrong but this is how i do it...

    If you are talking about the Model - Context use one. Since you only need one Model - Context in which to query - ie this is the database model.

    If you are talking about ObjectContext - then one for each Query (Linq). Take alook at this Performance Considerations for Entity Framework

    Rhys : A very good link, it has helped alleviate some fears about performance when creating many contexts.
  • It all depends on your app.

    A key consideration is that ObjectContext is not threadsafe so for a web app ObjectContext per request is the way to go.

    For a Win Forms app you can look at having longer-lived ObjectContexts. However, if you prefer to scope things more tightly I would try that first as opposed to prematurely optimizing it.

    More on Danny Simmons blog here.

    Rhys : Thanks for the link, it provided the information I need to feel comfortable creating different contexts for the situation in my question. Also I had not noticed the Detach method before so that will come in handy for future projects.

display application icon on UAC elevation prompt for application run from network share

I have configured my .NET application using an application manifest to request administrator privileges. I have also signed the assembly using signtool. Everything works great—when you start the application, you get the nice UAC prompt with the application's name and the name of the signing certificate.

However, when I run the application from a network share, the elevation prompt displays the generic executable icon, not my application's icon. How do I make the UAC prompt display my application's icon instead?

From stackoverflow
  • Could it be related to the question: Why does my .NET application crash when run from a network drive?

    That your .net application has other rights on the network share than on your local disk. Updating to 3.5 SP1 will normally remove this issue. Otherwise, check the policies for remote code for .net.

    Also you could try an other non .net application (procmon for instance) which required elevation to put it in the same dir and see what happens.

    Will Rogers : I did have to patch all the user machines to 3.5 SP1 to get the app to even launch from the network share. I've just tried your suggestion, running procmon from the share, and the same thing happens. Generic icon. So, it appears this might be a limitation of Windows?
    Davy Landman : it might be a feature of UAC, or a policy thing? I've just tried that, and indeed, UAC on a network location does not show the normal icon.
  • Apparently it's not something with .net, but with UAC.

    I've reproduced the behavior by placing procmon from systinternals on a network share and saw the same difference.

    Maybe it has something to do that when switching to an elevated session another user is used. The network mapping is done on the general user, so in the elevated session the application could not be found and therefor it's not possible to display the icon?

    You could try to do the following to force the connection to be valid on in the elevated session:

    • start an elevated command promt
    • net use \\your-network-location\share /user:<username> <password>
    • now go to start->run and start \\your-network-location\share\procmon.exe(to be on the safe side avoid a mapped drive) and see if the UAC prompt improves?
    Will Rogers : This process doesn't seem to make any difference.

DataContractSerializer within LINQ to SQL expression?

Hi, I'm new to LINQ expressions and trying to get the following to work:

public IQueryable<Models.Powerups.Powerup> GetPowerups(Guid userid)
 return from p in dc.Powerups
     where p.UserId == userid
     select (Models.Powerups.Powerup) new DataContractSerializer(Type.GetType(p.Type, true)).ReadObject(new XmlTextReader(new StringReader(p.Data)));

It obviously doesn't work since LINQ is trying to translate the entire expression to SQL.

Do you know a way to do this?

From stackoverflow
  • The best thing would be to do this:

    public IQueryable<Models.Powerups.Powerup> GetPowerups(Guid userid)
            return from p in dc.Powerups
                       where p.UserId == userid
                       select p.Data;

    Then deserialize the xml yourself once you get it back from the database. The LINQ to SQL provider will not know how to turn this into SQL and you wouldn't want it to anyways. The deserialization of serialized objects ought to happen in the CLR anyhow.

  • You need to break this into two parts, the first to get the data from the database, and then the transformation outside of that query for the data. You can use auto-generated iterators in C# to help:

    public IEnumerable<Models.Powerups.Powerup> GetPowerups(Guid userid)
      // Create the serializer here.
      DataContractSerializer s = new DataContractSerializer(typeof(Models.Powerups.Powerup));
      // Iterate through the powerups.
      foreach (var p in dc.Powerups)
        // Create the string reader, xml reader, then deserialize and return
        // instance.
        using (StringReader stringReader = new StringReader(p.Data))
        using (XmlTextReader xmlTextReader = new XmlTextReader(stringReader))
          // Return the deserialized instance.
          yield return (Models.Powerups.Powerup) s.ReadObject(xmlTextReader);

    The great thing about this is that it allows for deferred execution as well.

How do I do Perl machine or platform dependent TDD?

How do I go about testing a function or module that is machine or platform dependent? For example, something that looks at/depends on $^O or a module like Net::Ifconfig::Wrapper? I don't need to test that Net::Ifconfig::Wrapper is returning the correct values, but I do need to test whether or not I'm doing the right thing with those values.


EDIT: Testing $^O turned out to be easier than I thought:

    # <~> $ perl -e 'print $^O'
    # linux

    local $^O = 'linux';
    $rc = GetOSType();
    is($rc, $OS_LINUX, 'OS Check - linux');

For some reason I thought it was a read-only variable.

From stackoverflow
  • Why not a VM?

  • Generally you use mock objects to "fake up" the results of those system calls.

    During testing, use mock objects and have them return the various results you'd expect on different platforms, testing that your code reacts properly in those cases.

    Joe Casadonte : For whatever wacked-out reason, when I posted this I was thinking that I had to mock what Net::Ifconfig::Wrapper called, not Net::Ifconfig::Wrapper itself. I can only plead temporary insanity as a defense....
  • To follow up on Jason's mock objects suggestion, you should take a look at the article "Interfacing with hard-to-test third party controls" by Misko Hevery. It directly addresses testing third party components.

interface good practices

is it a good practice to have an interface that has no methods but just properties?

From stackoverflow
  • This would make sense if you were intending to have a set of data objects with a similar base structure.

  • It does not matter whether or not an interface has methods or not. The members that an interface exposes should be driven by the requirements of that interface's client.

  • Imagine that we have two different classes that don't derive from the same base: Users and Businesses. At some point in our project, we decide that Users and Businesses both need to have a reference to elements of an address, such as Street1, Street2, City, State, and Zip. We also have a proxy class of some sort that needs to be able to manipulate these values directly, regardless of the class they are defined in.

    One way to accomplish this would be to create an interface like so (example in c#):

    public interface IHasAddress {
      public string Street1 { get; set; }
      public string Street2 { get; set; }
      public string City { get; set; }
      public string State { get; set; }
      public string Zip { get; set; }

    Now, we can have a method in another class that does the following:

    public static class Test {
      public static void CheckZip(IHasAddress addressContainer) {
        if (addressContainer == null) return;
        if (addressContainer.Zip == "33314") addressContainer.State = "FL";

    As long as both User and Business implement the IHasAddress interface, the following code will compile and work as expected:

    User user = new User();
    Business business = new Business();

    This is a purely theoretical problem/solution, but it does prove a perfectly good need for this kind of structure.

  • This was a common way in Java to define a bunch of related constants before it got proper Enums.

  • I don't see anything wrong with it. If your application requires a contract to implement a bunch of properties, then so be it.

  • Don't forget that properties are nothing more than methods typically named get_PropertyName or set_PropertyName.

    So no, I see no issue with an interface that has only properties in it. They're still methods.

Defining classes in Java files

I have found one error in my Java program:

The public type abc class must be defined in its own class

How can I resolve this error? I am using Eclipse. I am new to Java programming.

From stackoverflow
  • A public class with the name of "abc" must be in a file called

  • Each source file must contain only one public class. A class named ClassName should be in a file named, and only that class should be defined there.

    Exceptions to this are anonymous and inner classes, but understanding you are a beginner to Java, that is an advanced topic. For now, keep one class per file.

    Answering your addition: it is OK to inherit classes and that's totally fine. This does not matter, each class should still have its own file.

    Jon Skeet : You can have multiple top-level classes in the same file, but only one *public* class. Only public classes have to conform to the filename rule (in terms of javac and Eclipse behaviour; a compiler could enforce this for non-public types - see spec reference above).
  • Public top-level classes (i.e. public classes which aren't nested within other classes) have to be defined in a file which matches the classname. So the code for class "Foo" must live in "".

    From the language specification, section 7.6:

    When packages are stored in a file system (§7.2.1), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:

    • The type is referred to by code in other compilation units of the package in which the type is declared.

    • The type is declared public (and therefore is potentially accessible from code in other packages).

    This rule, which doesn't have to be followed by compilers, is pretty much universally adhered to.

  • Ok, maybe an example will help.

    In file

    public class MySuperClass {
        // whatever goes here
    public class MySubClass1 extends MySuperClass {
        // compile error: public class MySubClass1 should be in
    class MySubClass2 extends MySuperClass {
        // no problem (non-public class does not have to be in a file of the same name)

    In file

    public class MySubClass3 extends MySuperClass {
        // no problem (public class in file of the same name)

    Does that make things clearer?

  • You can create a new class an a existing file if it's private, but you should not do this.

    Create one file per class. Eclipse does that for you, if you create a new class.

    For programming Java, you have to understand the construct of classes, packages and files. Even if Eclipse helps you, you have to know it for yourself. So start reading Java books or tutorials!

Java generics and array initialization

What's the explanation for the following:

public class GenericsTest {
    //statement 1
    public ArrayList<Integer>[] lists;

    public GenericsTest()
            //statement 2
     lists = new ArrayList<Integer>[4];

The compiler accepts statement 1. Statement 2 is flagged by the compiler for "generic array creation".

A good explanation I've seen regarding disallowing generic arrays is this one, arguing that since arrays are covariant and generics are not you could subvert the generic typing if you allowed generic arrays.

Leaving aside the argument over whether the language should go to the extreme lengths of creating this kind of complicated inconsistency in the treatment of generics to keep you from shooting yourself no matter how hard you try (and if anyone knows of any good discussions on the relative merits/demerits of the issue please post, I'd be interested to see the arguments), why should statement (1) be allowed if (2) isn't?

From stackoverflow
  • It's because you can't create, but you can use them:

    public class GenericsTest {
        //statement 1
        public ArrayList<Integer>[] lists;
        public GenericsTest()
            //statement 2
            lists = new ArrayList[4];
            //statement 3
            lists[0].add(new Integer(0));
            //statement 4
            lists[0].add(new String(""));

    Statement 3 is possible, statement 4 will lead to a compiler error.

    nsayer : Statement 4 does indeed give an error, but statement 2 gives an "unchecked conversion" warning, for what it's worth.
    Evan : Actually, I think the behaviour of statement 3 would be indeterminate, as you haven't done a "lists[0] = new ArrayList();" first...
    Sven Lilienthal : Hm, good shout. The example actually compiles (if you leave out statement 4) but I haven't run it. Statement 3 would then lead to a RuntimeException.
  • There seems to be obscure cases where you could inadvertently cause a ClassCastException as explained here (section 7.3)

    an intersting discussion on this topic could be found here

    Steve B. : Good references, thanks. Going to have to go through all this a bit more, I think.
  • In this case, I would avoid using arrays for just this reason. The declaration of "lists" in your original code could be

    List<List<Integer>> lists = new ArrayList<List<Integer>>(4);
    for(int i = 0; i < 4; i++) lists.add(null); // or add an empty ArrayList<Integer>

    (you should use the interface rather than the implementation in variable declarations)

    Instead of array [] syntax, you would use get() or set(). Other than that, it's equivalent.

  • This is explained pretty well in Effective Java (second edition), Item 25 - "Prefer lists to arrays". It's a book I can highly recommend!

    Effective Java

  • So the actual question is: Why is there no error for declaring a generic array? ?

    You will always get an error at the point you do something erroneous. Adding an error where there isn't technically a problem just adds to a clutter (although an editor might want to point that out to you).

    In some circumstances you may want to bend the rules a bit with an unchecked cast. There's no need to force the code to be littered with more warning suppressions than necessary (other than to point out the folly).

How do I tell Windsor to add an Interceptor to all components registered that implement IMustBeIntercepted

If I registered several components with Windsor.

IAnimal provides BigAnimal IPerson provides SmellyPerson IWhale provides BlueWhale

etc.. pretty standard component registeration

all the above types implement IMustBeIntercepted, how do I tell the container add an interceptor to all types that implement IMustBeImplemented so that when Resolve is called it is returned a BigAnimal with an interceptor as defined since it matches. I know I can do this for each one but its extra XML config or programatic config which I want to avoid

From stackoverflow
  • Simply create an interface like this:

    public interface IMustBeIntercepted {}

    and a facility like this:

    public class InterceptionFacility : AbstractFacility {
     protected override void Init() {
      Kernel.ComponentRegistered += new Castle.MicroKernel.ComponentDataDelegate(Kernel_ComponentRegistered);
     void Kernel_ComponentRegistered(string key, Castle.MicroKernel.IHandler handler) {
      if(typeof(IMustBeIntercepted).IsAssignableFrom(handler.ComponentModel.Implementation)) {
       handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(TestInterceptor)));

    Then register the facility to the container using the <facility> tag. Now all components that implements IMustBeIntercepted will be intercepted by the interceptor TestInterceptor.

  • Just wrote this baby:

     public static BasedOnDescriptor WithInterceptor(this BasedOnDescriptor reg, string interceptorComponentName) {
      return reg.Configure(x=> x.Configuration(
          "${" + interceptorComponentName + "}"