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.