Friday, April 29, 2011

Asp.Net LinkButton Onclick = method( container.dataitem ), need help with syntax

I have a linkbutton that I want to call a method in the code behind. The method takes a parameter of which I need to stick in a container.dataitem. I know the container.dataitem syntax is correct because I use it in other controls. What I don't know is how to user it a parameter for a method. Upon clicking on the button, the method should be called with the container.dataitem. The method is called 'AddFriend(string username)' Below is code. Thank you!

<asp:LinkButton ID="lbAddFriend" runat="server" OnClick='<%# "AddFriend(" +((System.Data.DataRowView)Container.DataItem)["UserName"]+ ")" %>' Text="AddFriend"></asp:LinkButton></td>
From stackoverflow
  • You need to use a ButtonField and handle the click in RowCommand. Check the MSDN docs

     <asp:buttonfield buttontype="Link" 
                      commandname="Add" 
                      text="Add"/>
    

    And in the code behind...

      void ContactsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
      {
        if(e.CommandName=="Add")
        {
             AddFriend(DataBinder.Eval(Container.DataItem, "Price""UserName"));
        }
      }
    
    : The linkbutton is in a datalist.
  • I think the same thing applies to a data list, but I've been using this for a repeater in my code behind. Mayby use DataListItemEventArgs and DataListCommandEventArgs in place of the Repeater.

    protected void rptUserInfo_Data(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            UserInfo oUserInfo = e.Item.DataItem as UserInfo;
    
            LinkButton hlUser = e.Item.FindControl("hlUser") as LinkButton;
            hlUser.Text = oUserInfo.Name;
            hlUser.CommandArgument = oUserInfo.UserID + ";" + oUserInfo.uName;
            hlUser.CommandName = "User";
        }
    }
    public void UserArtItem_Command(Object sende, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "User")
        {
            string command = e.CommandArgument.ToString();
            string[] split = command.Split(new Char[] { ';' });
    
            Session["ArtUserId"] = split[0];
            Session["ArtUserName"] = split[1];
            Response.Redirect("~/Author/" + split[1]);
        }
    }
    
  • Maybe this?

    <asp:LinkButton ID="lbAddFriend" runat="server"
     Text="Add Friend" OnCommand="AddFriend"
     CommandArgument='<%# Eval("UserName").ToString() %>' />
    

    Then in the code:

    Protected Sub AddFriend(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.CommandEventArgs)
        Dim UserName As String = e.CommandArgument
        'Rest of code
    End Sub
    

visual studio team suite : How to web test programmatically?

Good day,

I'm new to Visual Studio 2005 Team Suite web testing. Here's the action i'm trying to achieve.

On a webpage, I have a dropdownlist that is populated from a simple database table. In my tests, I want to click on each items of the dynamically populated dropdownlist, and after the postback, check if a label is visible on the page, which depends of the selected item in the dropdownlist.

However, since the dropdownlist is dynamically generated, I cannot simply 'record' and manually click on each item of the dropdownlist, so I have to code the test.

I'm pretty sure this is really simple to achieve, so I was wondering if there is a good free tutorial on web testing that I could use.

Thank you very much!

From stackoverflow
  • As long as it is fairly standard web-form postbacks you can use NUnitAsp:

    http://nunitasp.sourceforge.net/

    Here is a decent article on it here: ServerSide NUnitASP

    NUnitAsp is no longer really active or supported, but it still works good enough for simple form testing.

    YordanGeorgiev : It seems not be supported and developed anymore : http://nunitasp.sourceforge.net/
  • You question.

    However, since the dropdownlist is dynamically generated, I cannot simply 'record' and manually click on each item of the dropdownlist, so I have to code the test.

    It seems to me that you need add "Data Binding" to your test.

    Please read through this MSDN article.

    HTH.

  • Interesting. I will also try that. Thanks for all the suggestions

Splitting up a utility DLL into smaller components in C++

We have a core library in the form of a DLL that is used by more than one client application. It has gotten somewhat bloated and some applications need only a tiny fraction of the functionality that this DLL provides. So now we're looking at dividing this behemoth into smaller components.

My question is this: Can anyone recommend a path to take to divide this bloated DLL into a set of modules that have some interdepencies but do not necessarily require all other modules?

Here are the options as I see them but I'm hoping someone can offer other possibilities:

  1. Create a "core" dll and several "satellite" dlls which use the core and possibly other satellite DLLs.
  2. Subdivide the contents of the bloated DLL into static libraries that the main DLL uses (to maintain the same functionality) but apps that don't want to use the bloated version can assemble the static libraries they need into their own dll or into the app itself.

I was hesitant to mention this but I think it may be important to note that the app uses MFC.

Thanks for your thoughts.

From stackoverflow
  • Somewhat related to your question is this question, about splitting up a very large C module into smaller ones.

    http://stackoverflow.com/questions/748503/how-do-you-introduce-unit-testing-into-a-large-legacy-c-c-codebase

    It seems your question has to do with the larger question of breaking some large blob of code into a more modular system. The link above is definitely recommended reading.

    Karim : That is definitely part of it, but it has a lot to do also with the intricacies of dependencies and how difficult it would be to maintain this in a DLL environment vs. a static library. There are a lot of unknowns and I was hoping someone could guide me.
  • Without having all the details it is a little hard to help but here is what I would do in your situation

    • provide both static and dll versions of whate3ver you release - for MT and single threaded.
    • try to glean from the disparate clients which items should be grouped together to provide reasonable segmentation - without having layers of dependencies.

    having a "core" module sounds like a good idea - and make sure you don't have too many levels of dependencies - you might want to keep it simple.

    You may find after the exercise that one big dll is actually reasonable.

    Another consideration is that maintaining multiple DLLs and both static libs and DLLs will hugely increase the complexity of maintenance.

    Are you going to be releasing them all at once every time, or are they going to be mix and match? Be careful here - and know that you could create testing issues

    If no one is complaining about the size of the DLL then you might want to consider leaving it as is.

    Karim : I'm inclined to agree with your last point. There is a particular client who wants a customized version of the app that does less but is also much smaller. I would *much* rather talk them out of that that go to immense trouble of pursuing this.

PHP: "Global" Include

Current situation:

  • I have the current version of my MVC Framework which uses classes as controllers.
  • I have some "vintage" modules from my old MVC Framework which uses simple, flat includes as controllers.

Much simplified that means:

New Version:

<?PHP
class blaController extends baseController {
    private $intVar;

    function dosomethingFunction() {
        $this->intVar = 123;
        $this->view('myView');
    }
}
?>

Old Version:

<?PHP
$globalVar = 123;
// view "controllername" is automatically shown
?>

I'm now trying to write a wrapper to be able to use my old controllers in my new MVC without having to rewrite everything. To do so, I have a "wrapper" controller:

class wrapController extends baseController {
    function dosomethingFunction() {
        require 'old_dosomething.function.php';
        $this->view('old_dosomething_view');
    }
}

(Once again: This is VERY, VERY simplified - just to get the idea over. Not actual code.)

The problem with that approach is, that the previously global variable $globalVar now only exists inside of the method "dosomethingFunction" and cannot be accessed by the view.

This wouldn't be the case if I could force the require to behave as "in global scope" so that $globalVar would once again be available in global scope.

So: Is there some way to achieve "require_global" or something similar?

(One solution for my problem would be to modify my old controllers to start with a bunch of "global" commands, but I'd prefer a solution where I don't have to change so much of that old code.)

(Note: Please don't tell me that GLOBALS are bad. It totally misses the point of this question. Just accept that it is a requirement to keep some old code working in a newer, cleaner environment.)

From stackoverflow
  • Hmmm, this is an issue I've never before seen. I suppose you could do this

    class wrapController extends baseController {
        function dosomethingFunction() {
            require 'old_dosomething.function.php';
    
            // Force "old" globals into global scope
            $GLOBALS['globalVar'] = $globalVar;
    
            $this->view('old_dosomething_view');
        }
    }
    

    But that's a pretty tedious, manual process as well, depending on how many globals we're talking about. I'll think about this, but I don't know of any "auto-magic" solution off the top of my head.

    BlaM : "$GLOBALS['globalVar'] = $globalVar;" would be an option if I could iterate through all local variables, but is there an "automated" way to find all of those?
  • You can add local variables defined within dosomethingFunction() to global scope:

    class wrapController extends baseController {
        function dosomethingFunction() {
            require 'old_dosomething.function.php';
            //begin added code  
            $vararr = get_defined_vars();
            foreach($vararr as $varName => $varValue) 
                  $GLOBALS[$varName] = $varValue;            
            //end added code          
            $this->view('old_dosomething_view');
        }
    }
    

    Note, that for this to work as expected, you should call require before using any other thing in the function. get_defined_vars() returns only variables from the current scope, so no array_diff hacks are needed.

    BlaM : I'm not yet sure why, but somehow array_merge doesn't work in my scenario while merging the array "manually" with foreach works.
    vartec : well, $GLOBAL is not really "normal" array. Rolled back to foreach version.
  • This is the easiest solution I can think of.

    Use the get_defined_vars() function twice and get a diff of each call to determine what variables were introduced by the required file.

    Example:

    $__defined_vars       = get_defined_vars();
    require('old_dosomething.function.php');
    $__newly_defined_vars = array_diff_assoc($__defined_vars, get_defined_vars());
    $GLOBALS = array_merge($GLOBALS, $__newly_defined_vars);
    $this->view('old_dosomething_view');
    
    vartec : no need to do array_diff if you're calling that from within a function. get_defined_vars() only returns variables within the current scope.
    Matt : Good point. Though it's certainly possible that someone later adds variables to that function.
    BlaM : array_diff_assoc fails if one of the variables is an object that cannot be converted to string.
    vartec : @mcreenan: but if you call get_defined_vars() *before* more variables are added, they you'll get only the ones from included file.
  • Hi

    Have you tried Zend_Registry from Zend Framework?

    The registry is a container for storing objects and values in the application space. By storing the value in the registry, the same object is always available throughout your application. This mechanism is an alternative to using global storage.

    http://framework.zend.com/manual/en/zend.registry.html

    BlaM : That would require modifying the old code which is just what I try to avoid.
    BlaM : ... and I don't see how Zend_Registry is better than a simple global array to store stuff...
  • For anybody interested: My (so far) final version:

    class wrapController extends baseController {
        function dosomethingFunction() {
            // ... do some initialisation stuff ...
    
            $__defined_vars = array_keys(get_defined_vars());
    
            require 'old_dosomething.function.php';
    
            $__newly_defined_vars = array_diff(
                                        array_keys(get_defined_vars()),
                                        $__defined_vars, 
                                        array('__defined_vars')
                                    );
            foreach ($__newly_defined_vars as $var) {
                $GLOBALS[$var] = &$$var;
            }
    
            $this->view('old_dosomething_view');
        }
    }
    

    Ugly, but it works. Thanks for all your great help!

Cannot insert string into MySQL text column

For some reason, my queries screw up when I write to a column of type "text". Here is an example:

Describe messages;

Format is: Field Type Null Key Default

id  int(11) NO PRI NULL auto_increment
title   varchar(255) YES  NULL 
body    text YES  NULL 
to  text YES  NULL 
content_type    varchar(255) YES  NULL 
is_sms  tinyint(1) YES  NULL 
user_id int(11) YES  NULL 
created_at  datetime YES  NULL 
updated_at  datetime YES  NULL

Then I try an insert:

INSERT INTO messages (id,title,body,to) VALUES ('1','Test Message','This is a test message. This is a test message. This is a test message. This is a test message.', 'an email' );

For some reason this causes a general MySQL syntax error. The query works fine if I remove the "to" column and it's corresponding value from the query.

Any ideas?

From stackoverflow
  • 'to' is a reserved keyword in MySQL. You'll need to rename your column.

    http://dev.mysql.com/doc/refman/5.1/en/reserved-words.html

    However, Reserved words are permitted as identifiers if you quote them.

    http://dev.mysql.com/doc/refman/5.1/en/identifiers.html

  • INSERT
    INTO     messages (id,title,body,`to`)
    VALUES   ('1','Test Message','This is a test message. This is a test message. This is a test message. This is a test message.', 'an email' );
    
  • Try this instead

    INSERT INTO messages (`id`,`title`,`body`,`to`) 
       VALUES ('1','Test Message','This is a test message. 
       This is a test message. This is a test message. This is a test message.', 
       'an email' );
    
  • I believe if you surround the "to" with backtics like so:

    INSERT INTO messages (id,title,body,`to`) VALUES ('1','Test Message','This is a test message. This is a test message. This is a test message. This is a test message.', 'an email' );
    

    it will work - did for me anyway.

java Swing debugging headaches with Wacom pen tablet

I've been running up against a problem with Java Swing + my Wacom Graphire tablet for a few years in several Java applications and have now encountered it in my own.

I use a pen tablet to get around wrist issues while clicking a mouse, and it works fine under Windows except when I'm using Java applications. In Java applications, the single-click of the pen doesn't work correctly. (Usually the problem only occurs with file-selection dialog boxes or tree controls.) The pen tablet also comes with a wireless mouse that works with the same tablet, and its single-click does work correctly.

I don't know whether the problem is in the WACOM driver or in the Java Swing runtime for Windows or both. Has anyone encountered this before? I'd like to file a bug report with WACOM but I have no idea what to tell them.

I have been able to reproduce this in my own application that has a JEditorPane with an HTML document that I've added a HyperlinkListener to. I get HyperlinkEvent.ACTIVATED events on every single click with the mouse, but I do NOT get HyperlinkEvent.ACTIVATED events on every single click with the pen.

One big difference between a pen and a mouse is that when you click a button on a mouse, it's really easy to cause the button-click without mouse movement. On the pen tablet it is very hard to do this, and that seems to correlate with the lack of HyperlinkEvent.ACTIVATED events -- if I am very careful not to move the pen position when I tap the tablet, I think I can get ACTIVATED events.

Any suggestions for things to try so I can give WACOM some good information on this bug? It's really frustrating to not be able to use my pen with Java apps, especially since the pen works fine with "regular" Windows (non-Java) applications.

Normally I wouldn't ask this question here but I'd like to find out from a programmer's standpoint what might be going on so I can file a good bug report.

From stackoverflow
  • What you should do is add a mouseListener and see when it registers a mouseClicked(), mousePressed(), mouseReleased() event. I'm not sure if the swing reads the tablet pen as a mouse though. However, it should give you some insight into what's actually going on.

    Jason S : Great! I haven't used mouseListener before but it worked like a charm.
  • I think you already got the answer yourself: Moving the pen results in some other event than a simple click, perhaps maybe a Drag and drop like event. I'm not sure whether it's a Java/Swing or a Wacom problem, it could be that the tablet doesn't register the clicks as such but as drag events, or it could be that swing interprets the events incorrectly.

  • I tried dr.manhattan's suggestion and it works like a charm. I get mousePressed/mouseReleased events correctly; mouseClicked events happen always with the pen tablet mouse, but mouseClicked events do not happen with the pen unless I manage to keep the pen very still. Even a 1-pixel movement is enough to make it fail. I guess I should blame Java for this one: there's no way to specify a "click radius" for acceptible movement.

    package com.example.bugs;
    
    import java.awt.Dimension;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    
    import javax.swing.JFrame;
    
    public class WacomMouseClickBug {
        public static void main(String[] args) {
         JFrame jframe = new JFrame();
    
         jframe.addMouseListener(new MouseListener(){
          @Override public void mouseClicked(MouseEvent event) {
           System.out.println("mouseClicked: "+event);
          }
          @Override public void mouseEntered(MouseEvent event) {}
          @Override public void mouseExited(MouseEvent event) {}
          @Override public void mousePressed(MouseEvent event) {
           System.out.println("mousePressed: "+event);
          }
          @Override public void mouseReleased(MouseEvent event) {
           System.out.println("mouseReleased: "+event);    
          }   
         });
    
         jframe.setPreferredSize(new Dimension(400,400));  
         jframe.pack();
         jframe.setLocationRelativeTo(null);
         jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         jframe.setVisible(true);
        }
    }
    

How can I associate images with entities in Google App Engine

I'm working on a Google App Engine application, and have come to the point where I want to associate images on the filesystem to entities in the database.

I'm using the bulkupload_client.py script to upload entities to the database, but am stuck trying to figure out how to associate filesystem files to the entities. If an entity has the following images: main,detail,front,back I think I might want a naming scheme like this: <entity_key>_main.jpg

I suppose I could create a GUID for each entity and use that, but I'd rather not have to do that.

Any ideas?

I think I can't use the entity key since it might be different between local and production datastores, so I would have to rename all my images after a production bulkupload.

From stackoverflow
  • I see two options here based on my very limited knowledge of GAE.

    First, you can't actually write anything to the file system in GAE, right? That would mean that any images you want to include would have to be uploaded as a part of your webapp and would therefore have a static name and directory structure that is known and unchangeable. In this case, your idea of _main.jpg, OR /entity_key/main.jpg would work fine.

    The second option is to store the images as a blob in the database. This may allow for uploading images dynamically rather than having to upload a new version of the webapp every time you need to update images. It would quickly eat into your free database space. Here's some information on serving pictures from the database. http://code.google.com/appengine/articles/images.html

    MStodd : Yes, I would be uploading the images when I deploy the project. I think I can't use the entity key since it might be different when I bulkupload to my dev datastore and the production datastore.
    digitaljoel : yeah, you would need some sort of identifier that you have control over and is guaranteed not to change.
  • There is a GAE tutorial on how to Serve Dynamic Images with Google App Engine. Includes explanations & downloadable source code.

  • If you're uploading the images statically, you can use the key based scheme if you want: Simply assign a key name to the entities, and use that to find the associated images. You specify a key name (in the Python version) as the key_name constructor argument to an entity class:

    myentity = EntityClass(key_name="bleh", foo="bar", bar=123)
    myentity.put()
    

    and you can get the key name for an entity like so:

    myentity.key().name()
    

    It sounds like the datastore entities in question are basically static content, though, so perhaps you'd be better simply encoding them as literals in the source and thus having them in memory, or loading them at runtime from local datafiles, bypassing the need to query the datastore for them?