Friday, May 6, 2011

AS3 odd or even (mal)function

please how to fix this AS3 function ?

thank you

function dispari(numero:int):Boolean;
{
  //check if the number is odd or even
  if (numero % 2 == 0)
  {
    returns false;
  }
  else
  {
    returns true;
  }
}

ERROR: 1071: Syntax error: expected a definition keyword (such as function) after attribute returns, not false.

From stackoverflow
  • Why do you have a semi-colon (;) at the end of your function statement? I don't do any AS3 coding but it doesn't look right, and a cursory glance at a few samples on the web don't have it there.

    I suspect that may be what's causing your problem. Try this instead:

    function dispari(numero:int):Boolean
    {
        //check if the number is odd or even
        if (numero % 2 == 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    

    I've also changed the return statements to match what every other piece of AS3 does to return values (thanks, @Herms, forgot to mention that :-)

    Herms : exactly. The ; shouldn't be there.
    Herms : Oh, also note that it should be "return" not "returns". This answer's code has it correct.
  • Pax is correct with there answer, but I would also use the conditional operators for this small test.

    function dispari(numero:int):Boolean
    {
      return (numero % 2 != 0);
    }
    
    paxdiablo : or "return (numero % 2 != 0);" ?

Selecting resource file with GetGlobalResourceObject, reading against current culture

Hi,

I'm using GetGlobalResourceObject to localise the language on a website after setting CurrentUICulture depending on each users settings.

I am also creating an email using text retrieved via GetGlobalResourceObject which is sent to another user. Is it possible to select the language file used by GetGlobalResourceObject so that the email is sent in the language of the recipient rather than the sender (which happens by default).

Thanks, Patrick

From stackoverflow

How to pass information from one WPF UserControl to another WPF UserControl?

I've got a WPF application.

On the left side there is a stackpanel full of buttons.

On the right side there is an empty dockpanel.

When user clicks a button, it loads the corresponding UserControl (View) into the dockpanel:

private void btnGeneralClick(object sender, System.Windows.RoutedEventArgs e)
{
    PanelMainContent.Children.Clear();
    Button button = (Button)e.OriginalSource;
    Type type = this.GetType();
    Assembly assembly = type.Assembly;

    IBaseView userControl = UserControls[button.Tag.ToString()] as IBaseView;
    userControl.SetDataContext();

    PanelMainContent.Children.Add(userControl as UserControl);
}

This pattern works well since each UserControl is a View which has a ViewModel class which feeds it information which it gets from the Model, so the user can click from page to page and each page can carry out isolated functionality, such as editing all customers, saving to the database, etc.

Problem:

However, now, on one of these pages I want to have a ListBox with a list of Customers in it, and each customer has an "edit" button, and when that edit button is clicked, I want to fill the DockPanel with the EditSingleCustomer UserControl and pass it the Customer that it needs to edit.

I can load the EditCustomer usercontrol, but how do I pass it the customer to edit and set up its DataContext to edit that customer?

  • I can't pass it in the constructor since all the UserControls are already created and exist in a Dictionary in the MainWindow.xaml.cs.
  • so I created a PrepareUserControl method on each UserControl and pass the Customer to it and can display it with a textbox from code behind with x:Name="..." but that is not the point, I need to DataBind an ItemsControl to a ObservableCollection to take advantage of WPF's databinding functionality of course.
  • so I tried to bind the ListBox ItemSource in the View to its code behind like this:


<UserControl.Resources>
    <local:ManageSingleCustomer x:Key="CustomersDataProvider"/>
</UserControl.Resources>

<DockPanel>
    <ListBox ItemsSource="{Binding Path=CurrentCustomersBeingEdited, Source={StaticResource CustomersDataProvider}}"
             ItemTemplate="{DynamicResource allCustomersDataTemplate}"
             Style="{DynamicResource allCustomersListBox}">
    </ListBox>
</DockPanel>

which gets a stackoverflow error caused by an endless loop in the IntializeComponent() in that view. So I'm thinking I'm going about this in the wrong way, there must be some easier paradigm to simply pass commands from one UserControl to another UserControl in WPF (and before someone says "use WPF commanding", I already am using commanding on my UserControl that allows the user to edit all customers, which works fine, but I have to handle it in my code behind of my view (instead of in my viewmodel) since I need the parent window context to be able to load another user control when its finished saving:

<Button Style="{StaticResource formButton}" 
        Content="Save" 
        Command="local:Commands.SaveCustomer"
        CommandParameter="{Binding}"/>

private void OnSave(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
    Customer customer = e.Parameter as Customer;
    Customer.Save(customer);

    MainWindow parentShell = Window.GetWindow(this) as MainWindow;
    Button btnCustomers = parentShell.FindName("btnCustomers") as Button;
    btnCustomers.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
}

So how in WPF can I simply have a UserControl loaded in a DockPanel, inside that UserControl a button with a command on it that loads another UserControl and sends that UserControl a specific object to which it can bind its controls?

I can imagine I just do not know enough about WPF commands at this point, if anyone can point me in the right direction from here, that would be great, or if you think this "loading UserControls in a DockPanel pattern is foreign to WPF and should be avoided and replaced with another way to structure applications", that would be helpful news as well. You can download the current state of my application here to get an idea of how it is structured. Thanks.

From stackoverflow
  • I don't have the time to really dig into this (it's an interesting question and I hope you get a good answer-- I can see myself running into a similar situation in the future).

    Have you considered getting a little less WPF-y and falling back to firing an event on your source UserControl with an EventArgs that contains the customer, then in the event handler, firing the appropriate command on the target control?

  • This is where you use the Mediator pattern. There's several blog posts on this topic (for instance), and there's implementations of the pattern in some WPF frameworks (such as EventAggregator in Prism).

  • I've just finished a LOB application using WPF where this sort of problem/pattern appeared constantly, so here's how I would have solved your problem:

    1) In the DataTemplate where you create each item in the ListBox, along with it's edit button, bind the Button's tag property to the Customer object underlying that list box item.

    2) Create a Click event handler for the button, and set the Button's Click event to fire the handler.

    3) In the event handler, set the Content property of the UserControl.

    4) Set up a DataTemplate in scope of the User Control (perhaps in the resources of it's immediate container) which describes an editor for that single customer.

    Another approach that will work is to declare a Customer dependency property on your EditCustomer class, then set that property (perhaps through a XAML Trigger) when the button is clicked.

    I hope this isn't too vague. If nothing else, know that the problem you're facing is very solvable in WPF.

Cacti reports kilorows as a Mysql Sort

In my cacti installation, the graph that reports on mysql sorts has a value kiloRows. What does this value mean? I can't seem to find anything on it anywhere.

From stackoverflow
  • After looking through the source code, turns out cacti is taking the mysql SORT_ROWS variables, and dividing by 1024.

Possible problems switching from "ncalrpc" to "ncacn_np"

I have an application that uses RPC for interprocess communications. Turns out that synchronous RPC pipes used with "ncalrpc" protocol sequence are not alowed on Vista. I want to switch to "ncacn_np" and use RpcServerRegisterEpEx() with RPC_IF_ALLOW_LOCAL_ONLY flag.

Has anyone tried the same yet? Are there any possible problems associated with such transition?

From stackoverflow

How to handle Copy for multiple controls when adding a ShortcutKey to menu item?

If I do not create an "Edit->Copy" menu item and assign it the shortcut keys "CTRL+C", then I can select a control (RichTextBox, DataGridView, etc..) and hit "CTRL+C" and the control itself will handle the copy. I can copy text out, and paste it into notepad, etc..

Now throughout my whole form, I have a lot of controls. But I have a custom control that I want to make clear that I handle Copy functionality for. So I added the ShortcutKey CTRL+C to Edit->Copy, and by default it is set to Enabled.

Now, I have to implement an event handler for the 'click' event on that menu item. If I explicitly put in code to handle the copy, then it works:

public void menuEditCopy_Click(object sender, EventArgs e)
{
    myCustomControl.Copy();
}

However, now Copy does not work on any other type of control. My first inclination was to find out the type of control that has focus, and implement a limited set of copy code for each of them:

public void menuEditCopy_Click(object sender, EventArgs e)
{
    if (this.ActiveControl is MyCustomControl)
    {
        ((MyCustomControl)this.ActiveControl).Copy();
    }
    else if (this.ActiveControl is RichTextBox)
    {
        ((RichTextBox)this.ActiveControl).Copy();
    }
}

etc...

However, my controls are added to a SplitContainer, and debugging shows that this.ActiveControl is set to the splitcontainer instance, not the control, even though I know that control is selected.

So my last thought is to literally check if every control has focus:

public void menuEditCopy_Click(object sender, EventArgs e)
{
    if (myCustomControl.Focused)
    {
        myCustomControl.Copy();
    }
    else if (richTextBox1.Focused)
    {
        richTextBox1.Copy();
    }
}

I would like to avoid this if possible, it is a lot of controls, and if I add a new control, I would need to update it. Is there a better way of doing this?

Thanks

From stackoverflow
  • A SplitContainer implements ContainerControl, so you could check for either one and look for it's ActiveControl instead. ContainerControl is the base class, so I would go for that - you might catch another type of container as well:

    private void DoCopy(Control control)
    {
        if(control is ContainerControl)
            DoCopy(control.SelectedControl);
        else if(control is MyCustomControl)
            ((MyCustomControl)control).Copy();
        else if(control is RichTextBox)
            ((RichTextBox)control).Copy();
        else
            throw new NotSupportedException("The selected control can't copy!");
    }
    
    void menuEditCopy_Click(object sender, EventArgs e)
    {
        DoCopy(this.ActiveControl);
    }
    
  • You could try settting the KeyPreview property of your form to true. Then you could set up a handler for the form's KeyDown event which would look like the following:

    private void Form_KeyDown(object sender, KeyEventArgs e)
    {
        if(e.Modifiers == Keys.Control && e.KeyCode == Keys.C)
        {
            if (ActiveControl.GetType() == typeof(MyCustomControl))
            {
                ((MyCustomControl)ActiveControl).Copy();
                e.Handled = true;
            }
        }
    }
    

    Here you are specifying that you have handled the Ctrl-C event by setting the event args Handled property to true. Else, if you leave it as false, the Ctrl-C key press will be handled as per usual by each individual control.

    Because we have set the KeyPreview to true the form's handler gets to see each key press before any other control that it contains and can decide to deal with the key press itself or else allow it to be handled in the same way as if the form had never previewed it.

    I think as well it would be necessary to remove the short-cut key from your menu item (although you could still manually put the text "Ctrl+C" next to your menu item name) for this to work, otherwise your menu item will hijack the key stroke.

Dynamic Controls, Update Panels and Events - Best Way To Achieve My Result

Been pulling my hair out and doing a bit of looking on the web to try and figure out an elegant solution to my issue.

I have a ProductImages.aspx page. It shows all of the images associated with that product in a dynamically created list. Events are wired up to each picture to allow you to update it.

This works fine.

However, I have an option at the end which lets me add a new image. This is a button which fires off a call to the AddImage method.

Now what is happening is that the original controls are being create and added to the page with events. Then the button event if fired which recreates all of the existing image controls and a new one. Add this point the new image control create after the OnInit does not have events attached due to the events being added AFTER the OnInit.

I can do a Response.Redirect to reload the page and fire the OnInit to wire up the events again but this seems very inelegant and destroys the point of using update Panels.

Any ideas?

From stackoverflow
  • I'm thinking you could always load the picture upload control in a div and have a Javascript link to toggle the display attribute of the div.

    Or perhaps use CollapsiblePanels from the AjaxToolKit to hide and show the upload form.

    I think either of those ways would be more elegant than doing a post back (even if it's in an UpdatePanel) just to retrieve the picture upload form.

  • Your questions makes it sound like you're saying that you can't put the controls in OnInit because it is only fired on the first load of the page. This is not the case - OnInit is fired each time the page is loaded (including postbacks), so you can re-create your controls there even when using an update panel.

    One property that is different between the initial load and the postbacks is the Page.IsPostback property, which you can use to just perform actions on the first load of the page.

Are there any CSS lint tools?

I'm looking for a tool that can scan over a set of HTML pages, and check for bad or out of sync CSS usage. In particular, I want to check the following:

  1. Each CSS rule in the CSS files is used at least once by some HTML page.
  2. Each CSS class referenced on the HTML pages is actually defined in a CSS file.
  3. (Nice to have) that inline styles do not duplicate existing CSS classes (e.g. that there are no tags with inline styles for which there is an equivalent CSS class already defined).

Is there an existing tool that will do this?

From stackoverflow
  • W3 has a CSS checker.

    David Zaslavsky : That's just a validator, though - it checks for things like misspelled or nonexistent properties, but I don't think it does what the OP is asking.
    : No, it doesn't do any of what I'm looking for, unfortunaly. It also reports a lot of spurious errors, especially around IE hacks.
  • I'm not sure if it's an option, but Visual Studio will take care of #2 for you. It actually is kind of annoying when you're using classes that aren't styled, but used for Javascript.

  • I'm not sure if it has all of the requirements you have but I would definitely check out CSS Tidy. It is marketed as a CSS parser and optimizer.

    Otherwise, I'm not sure if there's anything out there besides good ol' "using good practices" while developing the project.

  • You might want to take a look at Dust-Me Selectors see also: http://www.sitepoint.com/dustmeselectors/

    I think it handles #1 and #2, but not sure about #3

    The Pixel Developer : Great tool + 1.
    : thanks! that was exactly what I wanted.

What would be a good browser-independent JavaScript programming environment?

My team's current project involves re-writing retrieval libraries in JavaScript. We are basically looking for a setup which enables us to apply test-driven development methods.

So far we plan to use Vim to write the code, no fancy IDE. For generating output we would use Spidermonkey's shell environment. JSLint could serve as a moderate syntax checking tool.

The essential question remains: How do you develop JavaScript (browser-independent) programs? If we are already on the right track, then maybe you can supply us with a few tips and tricks.

From stackoverflow
  • If you have the chance to rewrite it all, you might consider jQuery.

    It's essentially browser agnostic. Or at least it requires much less object sniffing than plain javascript.

  • Only testing you'll make your JavaScript code browser-independent.

  • You can test your code in Spidermonkey or Rhino (an older JS interpreter in Java), but you won't really know which browsers it works in until you test your scripts in them!

    I agree with the earlier poster, using a browser-independent library like jQuery is probably a good idea.

    I have not used Spidermonkey, but I know Rhino has a good debugging GUI, allowing the usual: setting breakpoints, watches, and stepping through code.

  • Yes,I'm using the same environment to develop standalone JS apps (vim + SpiderMonkey). I only would add up, that I've made small in-browser IDE for reading/writing/launching JS scripts on the server-side. Sometimes it's very helpful. Also, I'm looking for using WXJavascript project, which seems to be very promising.

Draw panel on a web site?

What is best way for making a draw panel in a web page. I would like to know how to develop something very simple,for example little panel where users can draw a signature.

This is great example drawhere.com, but I need something way simpler. Thanks

From stackoverflow
  • The easiest way to do this is probably with the <canvas> tag and some JavaScript. Here is a really simple example to get you started. You can add more functions for things like circles, boxes, etc.

    I'm sure somebody has already made something like this that you could use, but I couldn't find any.

  • Whilst Zifre's answer is valid in one sense, I would be very weary of the <canvas> tag, at least at the moment, due to there not being fantastic support for it (as many browsers don't yet fully support HTML5).

    Some browsers support it (most notably Firefox and anything running on Webkit), but swathes of others don't (especially older browsers). It's perhaps better to go for a more universal solution (though, by no means completely universal), and use something like Flash.

    Misha N. : Yes, for a moment I was amazed how simple it could be but then I saw that even IE7 does not have support for canvas. Thanks..
    Zifre : Just another reason not to use IE! Not that any technologically educated people really do...

Thursday, May 5, 2011

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

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

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

.. Like so:

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


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

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

            dc.SubmitChanges();
        }
    }
}

I am using the custom User class like so:

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

u.Insert();

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


Update:


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

enum AccessLevels
{
    Basic,
    Administrator
}


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

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

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

    i.e.

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

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

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

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

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

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

    or if you need to know the type:

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

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

    enum AccessLevels
    {
        Basic = 7,
        Administrator = 12
    }
    

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

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

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

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

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

Changing JTable cell color

This is driving me absolutely insane.

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

This is my current setup:

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

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

     // Formatting
     return c;
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

many music players like winamp do this too...

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

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

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

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

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

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

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

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

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

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

    Single-Instance C# Application - for .NET 2.0

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

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

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

does mysql 5.4 has a linux 32 bit version?

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

From stackoverflow

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

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

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

class Parent{
private:
  Child mychild;

public:
  void doSomething();
}

class Child{
public:
  void doOtherThing();
}

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

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

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

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

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

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

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

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

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

End to End testing of Webservices

Hi all, first time poster and TDD adopter. :-) I'll be a bit verbose so please bear with me.

I've recently started developing SOAP based web services using the Apache CXF framework, Spring and Commons Chain for implementing business flow. The problem I'm facing here is with testing the web services -- testing as in Unit testing and functional testing.

My first attempt at Unit testing was a complete failure. To keep the unit tests flexible, I used a Spring XML file to keep my test data in. Also, instead of creating instances of "components" to be tested, I retrieved them from my Spring Application context. The XML files which harbored data quickly got out of hand; creating object graphs in XML turned out to be a nightmare. Since the "components" to be tested were picked from the Spring Application Context, each test run loaded all the components involved in my application, the DAO objects used etc. Also, as opposed to the concept of unit test cases being centralized or concentrated on testing only the component, my unit tests started hitting databases, communicating with mail servers etc. Bad, really bad.

I knew what I had done wrong and started to think of ways to rectify it. Following an advice from one of the posts on this board, I looked up Mockito, the Java mocking framework so that I could do away with using real DAO classes and mail servers and just mock the functionality.

With unit tests a bit under control, this brings me to my second problem; the dependence on data. The web services which I have been developing have very little logic but heavy reliance on data. As an example, consider one of my components:

public class PaymentScheduleRetrievalComponent implements Command {
  public boolean execute(Context ctx) {
    Policy policy = (Policy)ctx.get("POLICY");
    List<PaymentSchedule> list = billingDAO.getPaymentStatementForPolicy(policy);
    ctx.put("PAYMENT_SCHEDULE_LIST", list);
    return false;
  }
}

A majority of my components follow the same route -- pick a domain object from the context, hit the DAO [we are using iBatis as the SQL mapper here] and retrieve the result.

So, now the questions:
- How are DAO classes tested esp when a single insertion or updation might leave the database in a "unstable" state [in cases where let's say 3 insertions into different tables actually form a single transaction]?
- What is the de-facto standard for functional testing web services which move around a lot of data i.e. mindless insertions/retrievals from the data store?

Your personal experiences/comments would be greatly appreciated. Please let me know in case I've missed out some details on my part in explaining the problem at hand.

-sasuke

From stackoverflow
  • I must say I don't really understand your exact problem. Is the problem that your database is left in an altered state after you've run the test?

  • First of all: Is there a reason you have to retrieve the subject under test (SUT) from the Spring Application context? For efficient unit testing you should be able to create the SUT without the context. It sounds like you have some hidden dependencies somewhere. That might be the root of some of your headache.

    How are DAO classes tested esp when a single insertion or updation might leave the database in a "unstable" state [in cases where let's say 3 insertions into different tables actually form a single transaction]?

    It seems you are worried about the database's constistency after you have running the tests. If possible use a own database for testing, where you don't need care about it. If you have such a sandbox database you can delete data as you wish. In this case I would do the following:

    1. Flag all your fake data with some common identifier, like putting a special prefix to a field.
    2. Before running the test drop a delete statement, which deletes the flagged data. If there is none, then nothing bad happens.
    3. Run your single DAO test. After that repeat step 2. for the next test.

    What is the de-facto standard for functional testing web services which move around a lot of data i.e. mindless insertions/retrievals from the data store?

    I am not aware of any. From the question your are asking I can infer that you have on one side the web service and on the other side the database. Split up the responsibilities. Have separate test suites for each side. One side just testing database access (as described above). On the other side just testing web service requests and responses. In this case it pays of the stub/fake/mock the layer talking to the network. Or consider https://wsunit.dev.java.net/.

    If the program is only shoving data in and out I think that there is not much behavior. If this is the case, then the hardest work is to unit test the database side and the web service side. The point is you can do unit testing without the need for "realistic" data. For functional testing you will need handrolled data, which is close to reality. This might be cumbersome, but if you already unit tested the database and web service parts intensively, this should reduce the need for "realistic" test cases considerably.

  • I must say I don't really understand your exact problem. Is the problem that your database is left in an altered state after you've run the test?

    Yes, there are actually two issues here. First one being the problem with the database left in an inconsistent state after running the test cases. The second one being that I'm looking for an elegant solution in terms of end-to-end testing of web services.

    For efficient unit testing you should be able to create the SUT without the context. It sounds like you have some hidden dependencies somewhere. That might be the root of some of your headache.

    That indeed was the root cause of my headaches which I am now about to do away with with the help of a mocking framework.

    It seems you are worried about the database's constistency after you have running the tests. If possible use a own database for testing, where you don't need care about it. If you have such a sandbox database you can delete data as you wish.

    This is indeed one of the solutions to the problem I mentioned in my previous post but this might not work in all the cases esp when integrating with a legacy system in which the database/data isn't in your control and in cases when some DAO methods require a certain data to be already present in a given set of tables. Should I look into database unit testing frameworks like DBUnit?

    In this case it pays of the stub/fake/mock the layer talking to the network. Or consider https://wsunit.dev.java.net/.

    Ah, looks interesting. I've also heard of tools like SOAPUI and the likes which can be used for functional testing. Has anyone here had any success with such tools?

    Thanks for all the answers and apologies for the ambiguous explanation; English isn't my first language.

    -sasuke

  • I would stay well away from the "Context as global hashmap" 'pattern' if I were you.

    Looks like you are testing your persistence mapping...

    You might want to take a look at: testing persistent objects without spring

  • I would recommend an in-memory database for running your unit tests against, such as HSQL. You can use this to create your schema on the fly (for example if you are using Hibernate, you can use your XML mappings files), then insert/update/delete as required before destroying the database at the end of your unit test. At no time will your test interfere with your actual database.

    For you second problem (end-to-end testing of web services), I have successfully unit tested CXF-based services in the past. The trick is to publish your web service using a light-weight web server at the beginning of your test (Jetty is ideal), then use CXF to point a client to your web service endpoint, run your calls, then finally shut down the Jetty instance hosting your web service once your unit test has completed.

    To achive this, you can use the JaxWsServerFactoryBean (server-side) and JaxWsProxyFactoryBean (client-side) classes provided with CXF, see this page for sample code:

    http://cwiki.apache.org/CXF20DOC/a-simple-jax-ws-service.html#AsimpleJAX-WSservice-Publishingyourservice

    I would also give a big thumbs up to SOAP UI for doing functional testing of your web service. JMeter is also extremely useful for stress testing web services, which is particularity important for those services doing database lookups.

When an swf (or other external remote resource) is loaded using SWFLoader, is there any client side caching performed.

Would like to know if when an external remote resource (say SWF, or JPG) is loaded using the SWFLoader (or even Image component) in flex3, if there is any client side (ie. browser caching?) or the loaded resources. In particular would a second request then to access a previously accessed resource just use the cached resource or would a new request be made. It would be nice to know if both are possible (ie. telling it to always use a fresh load or to use a cached copy if it is available)

From stackoverflow
  • If it's caching you might avoid it loading the resource with a random var. For example, loading the uri "/background.swf?var=1432".

  • You should empty your browser cache. This way, once everything works fine caching will still work. What means if I visit 5 times the same website I'll load it only once (that's really convinient).

    The solution ktulur suggests works but remember commenting/removing it when you finish.

    You could do something like:

    var anticache:String="";
    anticache = String(Math.random());
    var file_url:String = "Whatever.xxx"+anticache;
    

    An then comment/uncomment the second line to use/ignore the anticache method. I hope it helps :)

  • The browser is responsible for caching all externally loaded media, such as images sounds, videos and even SWFs. These can be deleted by clearing your browser cache. I recommend the Clear Cache Button Firefox Add-on for anyone testing there Flash projects in Firefox.

    However, Flash Player handles caching of any externally loaded signed Flash components e.g. any Adobe Flex framework components. You can read more about Flash Players cache here. Clearing your browser cache, will not clear these components.

    To stop a file being cached by your browser, you will need to make sure its filename is unique each time it is loaded. You can do this by appending a random string as a URL variable. I usually use the current time, or a random number:

    var noCache:int = new Date().getTime();
    myImage.load("filename.jpg?uniq=" + noCache);
    

    Or you can add the unique variable using the URLVariables class.

Trouble with seekp() to replace portion of file in binary mode

Hi,

I'm having some trouble with replacing a portion of a file in binary mode. For some reason my seekp() line is not placing the file pointer at the desired position. Right now its appending the new contents to the end of the file instead of replacing the desired portion.

long int pos;
bool found = false;
fstream file(fileName, ios::binary|ios::out|ios::in);

file.read(reinterpret_cast<char *>(&record), sizeof(Person));

while (!file.eof())
{   
    if (record.getNumber() == number) {
       pos=file.tellg();
       found = true;
       break;
}

// the record object is updated here

file.seekp(pos, ios::beg); //this is not placing the file pointer at the desired place
file.write(reinterpret_cast<const char *>(&record), sizeof(Person));
cout << "Record updated." << endl;
file.close();

Am I doing something wrong?

Thanks a lot in advance.

From stackoverflow
  • I don't see how your while() loop can work. In general, you should not test for eof() but instead test if a read operation worked.

    The following code writes a record to a file (which must exist) and then overwrites it:

    #include <iostream>
    #include <fstream>
    using namespace std; 
    
    struct P {
        int n;
    };
    
    int main() {
      fstream file( "afile.dat" , ios::binary|ios::out|ios::in);
      P p;
      p.n = 1;
      file.write( (char*)&p, sizeof(p) );
      p.n = 2;
      int pos = 0;
      file.seekp(pos, ios::beg);
      file.write( (char*)&p, sizeof(p) );
    }
    
  • while (!file.eof())
    {   
        if (record.getNumber() == number) {
           pos=file.tellg();
           found = true;
           break;
    }
    

    here -- you`re not updating number nor record -- so basically you go through all file and write in "some" location (pos isn't inited)

    And Neil Butterworth is right (posted while i typed 8)) seems like you omitted smth

Suggestions for (semi) securing high-scores in Flash/PHP game...

...I have read a few threads on here that have discussed various methods and was just looking for some feedback on a proposed solution we came up with. In one of the threads a comment was posted recommending a public/private key which sounded great, this is what we were thinking...

Client Side - 1. Key is stored inside of Flash swf which is encrypted using 3rd party tool. 2. High score is hashed along with high-score value (EX: md5 ('ourSecretKey' + 200)) 3. This value is sent via AMF to a PHP script on the server, along with the high-score (200)

Server Side - 1. Server receives data and hashes the passed high-score (200) + secret key ('ourSecretKey' stored on the server as well as in Flash) and checks against the passed hash if the value is a match it allows the high-score to be entered, else FAIL.

I know this isn't a foolproof solution but would this be acceptable? I mean would this be sufficient security on a high-score form for a simple online Flash game? Thoughts?

Thank you in advance!

From stackoverflow
  • For a ridiculously short value ( Ie: values < 64 characters ), MD5 as a hash becomes ineffective due to rainbow table attacks, and as the value you're sending will be shared over the wire, all they have to do is brute force the shared secret ( and they have a known product to work with )

    As such, thats not public key private key. its mererly shared secret.

    Also, keep in mind this shared secret will be in your flash file you send to the user, which these days and be trivially disassembled and then your "secret" is not a secret any more.

    You want a more challenge-response mechanism with proper crypto signing, where a new sign key is assigned for every game from the server, and multiple scores cannot be submitted with the same sign key. ( For extra protection ;) )

    1. User starts game. Sign key is requested. ( the sign key is produced from another key which they cant access ).
    2. Score is signed with sign key, and then sent
    3. You verify the value of the sign with the key you sent them.
    4. You discard the sign key you sent them.

    However, you still have the problem where you have no way to prevent the actual scoring system being tampered with. Somebody smart enough could just reverse engineer your SWF object and inject new code that just sets the score to their chosen value.

  • The answer to your question is, it depends. It depends mainly of the estimated popularity of your game.

    From a security perspective, your solution is about as secure as sending the highscore in cleartext. What you're doing here is called security by obscurity, which, according to who you listen to may have its benefits in some cases. In this case it's probably that Joe the average user would not likely be able to crack it himself. For anyone with some l33t h4xxor skillz you might as well send it all in cleartext. If all you want is to stop Joe, then it's probably enough, at least until someone creates a fake client for Joe to download (which depending on the popularity of your game could take anything from a couple of days to never (or faster if it's WoW)).

    A better solution is the one given by @Kent Fredric. However as it says it doesn't solve the problem of someone creating a fake client. A solution to that might be something like this:

    1. Give every action a player can perform an id.
    2. Store every action the player performs in a list of ids.
    3. When the game is over hash the score, the list of actions and encrypt it with the public key received from the server. (see Kent Fredric's post for details on this)
    4. Send the encrypted hash (more commonly called digital signature) to the server together with the score and the list of actions performed.
    5. Let the server "play" the game according to the actions in the list.
    6. Verify that the same score was attained.
    7. Verify that the digital signature is correct.
    8. Update server highscore list.

    This will guarantee two things:

    1. The score comes from the correct client.
    2. The score is correct in regards to the game played.

    But there's still one serious flaw to this scheme. There's no way of knowing that the game was in fact actually played. If the client is compromised, the list could just be a prefab of a "prefect game" that is sent to the server. It's not possible to directly tamper with the scoring system, but with enough effort someone will most likely be able to create a list of actions that comprise a "perfect game".

    However it gives a little bit stronger guarantee than just using the solution in Kent Fredric's post. To solve the whole problem would mean that you must validate the client somehow. This is very difficult since most ways of doing this are easily circumvented.

    Finally I just had to comment on your choice of hash algorithm: MD5 is a great hash algorithm for those still living in the nineties. For the rest of us I recommend SHA-2 or at least SHA-1.

  • Blockquote Finally I just had to comment on your choice of hash algorithm: MD5 is a great hash algorithm for those still living in the nineties. For the rest of us I recommend SHA-2 or at least SHA-1.

    Bah I knew I should have mentioned SHA instead :)

    If I do use something like a swf encrypter application to encrypt the swf code wouldn't that at least make it quite a bit more difficult to get at the key stored in Flash? I would think that without that key (or at least without getting to it easily) it would be a huge pain to figure out what was being used to generate the hash that is sent off to the server.

    Something like this is what I was thinking of: SWF Encrypt

    Thank you all again for these answers, this is amazingly helpful. Oh and this will just be a simple Flash game sent out by a client to customers, something fun to pass time at work over the holidays.

  • If the distribution of your game is limited and there's no real money/bounty involved for the players to win, your original scheme is probably enough.

    Using SWF Encrypt will likely make it a little bit more difficult to extract the key, and it could be a good tool to use even in a more advanced system as well. But if you have a real public/private key scheme (e.g. RSA), it's really a moot point since the public key isn't a secret, it's not supposed to be. Still to prevent most people from editing the code and tamper with the scoring system, SWF Encrypt is probably a good enough choice.


    Just to make you a bit more paranoid I wrote the following as well:

    The problem with SWF Encrypt, as with most other similar tools, is that it must still be possible to execute the script on a (possibly compromised) machine. So all information must be available on said machine. Compare that with a classic use of cryptography, sending messages:

    When you send an encrypted message, you typically trust the source and the destination, so both of these have the key to decrypt the message. What you don't trust is the courier, or at least not that your enemies will not intercept the courier. So the courier does not have they key and your message is safe.

    Your problem is instead that in your case you trust the destination (you) but not the source (the client) or vice versa. Still you need the source to be able to encrypt the message since you trust the courier even less. So the source needs to have all information to encrypt and decrypt messages in order to function. Your problem is that you cannot see the difference between a "good" source and a "bad" source.

    What I mean is that since the code must still be possible to run on a client, the information to do so must be fully available, albeit possibly in obscured form. A hacker could for instance create her own ActionScript compiler that transform the obfuscated ActionScript code into something readable and make appropriate changes. Difficult but definitely doable.

    Yet this level of sophisticated attacks will most likely not be a problem for you, if you have a limited distribution and no real bounty to win.

  • I don't see any advantage of using the solution, Kent mentioned. As a client, I can request that server side created key. Ok I can't use it more than one time, but i don't have to ... every time I need one i just request it.

    1. So i request the key.
    2. Make my own highscore
    3. Hash the highscore with the key.
    4. Send the highscore to server
    5. The server use the submitted key to get the highscore back.
  • I'm not sure which ones you've read, but this one has a top answer:

    http://stackoverflow.com/questions/73947/what-is-the-best-way-to-stop-people-hacking-the-php-based-highscore-table-of-a-f

    HTH

  • Wow

    Pretty hard solutions 8).

    I implemented system like this once. Although it won`t work for every game out there...

    You should replay the game on server. When user play -- you store "state changes" and then simply feed it to you game in some kind of "replay" mode.