Wednesday, April 20, 2011

How to get textbox value from client side and create query string from it?

I'm using jquery for modal dialogs. I want to open model dialog from one page and to send some additional query string to modal dialog page. something like this:

 <asp:HyperLink ID="hypClientSearch" runat="server" NavigateUrl="~/SomePage.aspx?KeepThis=true&additionalQS='<%= txtBox.Text %>'&TB_iframe=true&height=650&width=800&modal=true" CssClass="thickbox" >

This example doesn't work. Does anyone know the solution?

From stackoverflow
  • Try this in the modal dialog when it opens (this is client side javascript):

    var textBoxValue = window.opener.document.getElementById("txtBoxId").value;
    

    You then use Javascript to insert the additional info into the correct place in the dialog, for example using JQuery.

  • In addition to Helgi's answer.
    If you want to get the value of the textbox using jQuery (for when you need to use other selectors then the id) you can use:

    var textBoxValue = $(textBoxSelector, window.opener.document).val();
    

    Edit
    Oh I just noticed that your using modal. Then the page is opened in an iFrame, you can get the value from within the iFrame using:

    var textBoxValue = $(textBoxSelector, window.parent.document).val();
    

    Also if you need to send it to the server at the iFrame request try editing the href attribite of the link on click:

    $('#hypClientSearch').click( function() {
     var textBoxContent = $(textBoxSelector).val();
     $(this).attr('href', 'somepage.aspx?textbox='+textBoxContent+'&otherVarsForModal=foo');
     //we let the event bubble for the modal plugin, so ne returning false here
    });
    

Website localization depending on its extension

Hello,

I'm currently building my personal website in ASP.Net MVC and I want two versions: a French and an English one.

I've got two domain names and I want to match the English version to the ".com" domain and the French version to the ".fr" domain:

  • When you go to www.mywebsite.fr, you will get the French version
  • When you go to www.mywebsite.com, you will get the English version

So, my question is: What is the best (easiest?) way to handle this?

Thanks

From stackoverflow
  • A quick overview: use ASP.NET Localization infrastructure to enable localization (there's plenty of stuff for localizing ASP.NET MVC-based sites) and add section to your Web.config that would map .com to en-US, and .fr to fr-Whatever.

Automated tests: mocking vs creating test object graph ( using IoC container), what is better under what conditions?

How do you decide what to choose:

  1. use mock objects for a test OR
  2. create a test object/ object graph using an IoC framework and run test on that data
From stackoverflow
  • I am very happy with using IoC for much of my app, and especially I appreciate that test-datasources can be injected for testing.

    For more problematic backend connections (currently a single ESB call) or functions that need complicated state I mock.

  • For unit tests: If an object is not the object tested, mock or stub it. In that way, you can directly control it so it returns the data that you want.

    If you create a test object/object-graph, you have to set it up so that it provides the data that you want. That is probably a lot more work than you want.

    For integration tests, of course you'd test a whole object graph at a time.

  • If you need to write a lot of initialization code - a mocking framework would probably help you write better, easy to understand Unit Tests.

    There is no need to re write code that a mocking framework can save you.

  • It depends what you are trying to test. Unit tests with collaborators mocked out are great because

    • They are really, really fast
    • They are small and easy to understand
    • They don't have dependencies on the wider world which makes them easy to run
    • They provide excellent defect localisation

    However, pure unit tests cannot tell you if you have configured your objects correctly in your IoC container, if the database connection string works etc. You need a test which runs up your IoC container and really reaches out to the Db to prove these things.

    If you write as many of your tests as pure, standalone unit tests as possible then your build will stay fast. This is crucial, as a slow bulid gets run less. Even so, don't forget to add a sprinkling of wired tests to prove that your application'hangs together'.

    For example, we have a (single) test for every service in our container that proves that we can request it from the IoC container. This proves we're wired up, from then on it is unit tests all the way. We have lots of pure unit tests.

    The whole lot is then wrapped in some application level functional tests to prove that the app itself does what the user wants.

    The thing to bear in mind is the time cost of each test type. Moving from pure unit -> wired -> functional tests costs an order of magnitude of execution time and complexity when they break.

problem with using XPath to locate some part of XML

Duplicate of

HOw to make the text repeat only once every for-each?

I have problem with using XPATH to point to some element in XML. Here is my XML code:

    <character>
      <name>some name </some name>
    </character>

  </quote>
 <quote>
  ....
  </quote>
 </quotes>

and here My XSLT code:

<xsl:for-each select="quotes/quote">
    <xsl:value-of select="quotes/quote/character/name"/>
 </xsl:for-each>

WHat I try to do is that I try to list the name of character for every quote. BUt this code does not work WOuld you please help me with this problem? Thank you

From stackoverflow
  • The error is:
    You use quotes/quote twice

    You might try this one:

    <xsl:for-each select="quotes/quote">
      <xsl:value-of select="character/name"/>
    </xsl:for-each>
    
  • Inside the for-each, the context node is quote - so it looks like you just need:

    <xsl:for-each select="quotes/quote">
        <xsl:value-of select="character/name"/>
    </xsl:for-each>
    

    Of course, the purists would argue that it would be better to use a match:

    <xsl:apply-templates select="quotes/quote" />
    ...
    <xsl:template match="quote">
        <xsl:value-of select="character/name"/>
    </xsl:template>
    

send form data as web service in symfony

I am making a restrictive portal to a WiFi network using symfony, and I want to send a form as web service to other sites that want to use this portal. How should I solve this? I realize I could go the SOAP/WSDL route, but since symfony is already RESTful, it seems to me I could go the RESTful route with considerably less pain and loss of performance.

Right now, I have a working form, but I've only made a casual attempt to bring the form to a remote site by using cURL. The form does not work remotely since the routing is not set up correctly (I think). Can someone help me with this?

Thanks.

From stackoverflow
  • Hello,

    to call restfull service somewhere you simply call its URL and read result. Do you have any example of what exactly is not working? Does "other" service support restfull calls? :) I hope so.

    Calling rest service is really as easy as opening a website with some parameters in URL. So I am wondering what should not work. You can use some simplexmlreader or such to read restful services directly if you don't have blocked access to that remote service.

FindBugs not accepting bcel.jar in ANT script

I installed findbugs into my ant lib directory and added the following code into my main ANT script:

<target name="findbugs" depends="init">

    <findbugs home="C:\\findbugs\\" output="html outputFile="C:\\findbugs\\out.html" jvmargs="-Xms512M">
        <sourcePath path="${messageaggregator.src}" />
        <class location="${messageaggregator.src}"/>


    </findbugs>
</target>

The following xml is called within the init target:

<taskdef name="findbugs" classname="edu.umd.cs.findbugs.anttask.FindBugsTask">

On running the ANT script, all I get is the following output:

findbugs:
    [findbugs] Executing findbugs from ant task
    [findbugs] Running FindBugs...
    [findbugs] BCEL class compatability error.
    [findbugs] The version of class org.apache.bcel.generic.ObjectType found was not compatible with
    [findbugs] FindBugs.  Please remove any BCEL libraries that may be interfering. This may happen
    [findbugs] if you have an old version of BCEL or a library that includes an old version of BCEL
    [findbugs] in an "endorsed" directory.
    [findbugs] Output saved to C:\\findbugs\\out.html

Why is findbugs not working?

From stackoverflow
  • You've got a conflict with an older version of BCEL that you have to get rid of. It might be in your jre/lib/ext directory (bad idea), or part of the CLASSPATH that you've got for your project, or maybe part of the Ant /lib. In any case, you should find all the BCEL JARs in your CLASSPATH, remove them, and update them with the version that FindBugs requires.

  • If findbugs has its own version of BCEL then why do I get this error:

    [findbugs] Executing findbugs from ant task
    [findbugs] Running FindBugs...
    [findbugs] The java class is not found:  org.apache.bcel.classfile.ClassFormatException
    [findbugs] Output saved to C:\\findbugs\\out.html
    

    This error occurs if I remove bcel.jar from the findbugs.home directory.

  • I have the same problem with class not found. I need to add paths to external jars (jars are placed in different directory than findbug.jar) for findbug inlcuding bcel.jar into its classpath. But even classpath is right, this error is occuring.

  • Java Version 1.6.0_06 contain old BCEL library.

    java version "1.6.0_06" Java(TM) SE Runtime Environment (build 1.6.0_06-b02) Java HotSpot(TM) Client VM (build 10.0-b22, mixed mode)

    Once I change to 1.5.0_17 it works fine for me.

Two-way relation in JPA

Hi

I have the two entity classes, User and MyCharacter. User has a list of MyCharacters and each MyCharacter has a reference back to the User (owner). What I'd like to accomplish is, that I use the same join table for both relations, meaning, that the owner relation found in MyCharacter would automatically use the same join table as from User=>MyCharacter. This means that the getOwner() method in MyCharacter should work without me having to explicitly at some point call setOwner(user).

To clear this a bit more, here's my unit test which currently fails (last assert fails)


@Test
public void testTwoWayRelation() {
    User user = new User();
    MyCharacter character = new MyCharacter();
    List<MyCharacter> chars = new ArrayList<MyCharacter>();
    chars.add(character);
    user.setCharacters(chars);

    facade.store(user);
    assertNotNull(character.getId());

    character = facade.find(MyCharacter.class, character.getId());

    assertNotNull(character.getOwner());
}

My entity classes are listed below.


@Entity
@Table(name = "myuser")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    protected Long id;

    @OneToMany(cascade = { CascadeType.PERSIST })
    protected List<MyCharacter> characters;

    public User() {

    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }


    public List<MyCharacter> getCharacters() {
     return characters;
    }

    public void setCharacters(List<MyCharacter> characters) {
     this.characters = characters;
    }

}


@Entity
public class MyCharacter{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    protected Long id;

    @ManyToOne
    @JoinTable(name = "myuser_mycharacter", joinColumns = @JoinColumn(name = "characters_id"), inverseJoinColumns = { @JoinColumn(name = "user_id") })
    protected User owner;

    public MyCharacter() {

    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }


    public User getOwner() {
     return owner;
    }

    public void setOwner(User owner) {
     this.owner = owner;
    }
}
From stackoverflow
  • Here is an article from Oracle which explains how to map such relations.

    When you use this in Java, depending on your JPA framework, you will need to add the MyCharacter to the list in User and set the user field in MyCharacter or only one of the two (because the framework will manage the other side for you). I suggest to write a small test to figure out what works (and you should write test cases for all the way in which you use your objects, anyway).

    When objects are loaded from the database, you won't need to do that since all frameworks handle this case correctly.

  • That's how we join two entities with jpa in our project:

        @Entity
        @Table(name = "Period")
        public class Period implements Serializable {
          private List<Delay> delays = new ArrayList<Delay>();
    
          @OneToMany(mappedBy="period") //name of the field in joined entity
          public List<Delay> getDelays() {
          return delays;
          }
        }
    
       @Entity
       @Table(name = "Delay")
       public class Delay implements Serializable {
    
        private Period period;
    
        @ManyToOne
        @JoinColumn(name = "PERIODID")
        public Period getPeriod() {
           return period;
        }   
    }
    
  • i'm not sure i understand your problem correctly, but you could try to set mappedBy on MyCharacter.owner:

    @ManyToOne(mappedBy="characters")
    

How can I get value of textbox on a user control

Hi All, I have a user control which has a textbox on it, now this usercontrol is on another user control which I am using on aspx page how can I get value of the textbox on the first user control.

From stackoverflow
  • Write a property in your usercontrol to expose its contents, e.g.,

    public string TextBoxValue
    {
        get { return txtControl1.Text; }
    }
    

    This way you can get the value of the textbox without exposing the whole textbox control as a public object.

  • Jon Limjap's answer provides the best solution for this kind of problem - Expose control values using Public properties.

    However, if you do not want to do it this way (or you have to do this for a lot of controls and want to avoid creating Public properties for each control), you could use Reflection to "find the control" in the ChildControls of the required UserControl:

    TextBox txt = UserControl1.FindControl("myTextBox") as TextBox;
    
    if (txt != null)
    {
      string val = txt.Text;
    }
    

Return a value from batch files (.bat file)to a text file.

hi,

I have a .bat file shown below

@echo off 
for /f "delims=" %%a in ('C:\MyProj\Sources\SearchString.vbs') do (
set ScriptOut=%%a)
#echo Script Result = %ScriptOut%
echo %ScriptOut% >C:\ThreePartition\Sources\myfile.txt

I want my output variable which is ScriptOut to be stored into a text file. Can anyone suggest any method to be added to my existing batch file.

Thanks Maddy

From stackoverflow
  • Do I understand correctly that your file gets overwritten and you want it appended? If so, try this:

    echo %ScriptOut% >> C:\ThreePartition\Sources\myfile.txt
    

    (note the double ">>")

    Maddy : hi, No actually i get a value returned to ScriptOut(Returned frm vbs) which should be written into a text file.When i run this above code,i just get ECHO is OFF in the myfile.txt
    Stanislav Kniazev : Then the blank line is your problem as Johannes Rössel pointed out.
    Maddy : I didnt get it Johannes??.Which blank line could be the problem.Why am i getting ECH is OFF in my Myfile.txt.??
    Lucas Jones : The reason you are getting ECHO OFF is that ECHO is being passed noting, or just whitespace (ie a blank line). In this case, ECHO prints whether command-echoing is turned on. (It just so happens that you turned off that with your 'ECHO OFF' at the top) This has no effect on whether it will redirect.
    Joey : I elaborated a little more, hopefully that made it somewhat clearer
  • The for loop you have there executes that script and runs for every line the script returns. Basically this means that your environment variable %ScriptOut% contains only the last line of the output (since it gets overwritten each time the loop processes another line). So if your script returns

    a
    b
    c
    

    then %ScriptOut% will contain only c. If the last line is empty or contains only spaces iot will effectively delete %ScriptOut% which is why when you do an

    echo %ScriptOut%
    

    you'll only get ECHO is on. since after variable substition all that's left there is echo. You can use

    echo.%ScriptOut%

    in which case you'll be getting an empty line (which would be what %ScriptOut% contains at that point.

    If you want to print every line the script returns to a file then you can do that much easier by simply doing a

    cscript C:\MyProj\Sources\SearchString.vbs > C:\ThreePartition\Sources\myfile.txt
    

    or use >> for redirection if you want the output to be appended to the file, as Stanislav Kniazev pointed out.

    If you just want to store the last non-empty line, then the following might work:

    for /f "delims=" %%a in ('C:\MyProj\Sources\SearchString.vbs') do (
      if not "%%a"=="" set ScriptOut=%%a
    )
    

    which will only set %ScriptOut% in case the loop variable isn't empty.

How To Get The List Of Properties Of Class?

How do I get a list of all the properties of a class?

From stackoverflow
  • Reflection; for an instance:

    obj.GetType().GetPropeties();
    

    for a type:

    typeof(Foo).GetProperties();
    

    for example:

    class Foo {
        public int A {get;set;}
        public string B {get;set;}
    }
    ...
    Foo foo = new Foo {A = 1, B = "abc"};
    foreach(var prop in foo.GetType().GetProperties()) {
        Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null));
    }
    


    Following feedback...

    • To get the value of static properties, pass null as the first argument to GetValue
    • To look at non-public properties, use (for example) GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) (which returns all public/private instance properties ).
    Marc Gravell : For completeness, there is also the ComponentModel, exposed by TypeDescriptor.GetProperties(...) - which allows dynamic runtime properties (reflection is fixed at compile-time).
    Richard : Suggestion: Expand answer to cover protected/private/static/inherited properties.
  • You can use reflection.

    Type typeOfMyObject = myObject.GetType();
    PropertyInfo[] properties =typeOfMyObject.GetProperties();
    
  • You can use Reflection to do this: (from my library - this gets the names and values)

    public static Dictionary<string, object> DictionaryFromType(object atype)
        {
            if (atype == null) return new Dictionary<string, object>();
            Type t = atype.GetType();
            PropertyInfo[] props = t.GetProperties();
            Dictionary<string, object> dict = new Dictionary<string, object>();
            foreach (PropertyInfo prp in props)
            {
                object value = prp.GetValue(atype, new object[]{});
                dict.Add(prp.Name, value);
            }
            return dict;
        }
    

    This thing will not work for properties with an index - for that (it's getting unwieldy):

    public static Dictionary<string, object> DictionaryFromType(object atype, 
         Dictionary<string, object[]> indexers)
    {
         /* replace GetValue() call above with: */
         object value = prp.GetValue(atype, ((indexers.ContainsKey(prp.Name)?indexers[prp.Name]:new string[]{});
    }
    

    Also, to get only public properties: (see MSDN on BindingFlags enum)

    /* replace */
    PropertyInfo[] props = t.GetProperties();
    /* with */
    PropertyInfo[] props = t.GetProperties(BindingFlags.Public)
    

    This works on anonymous types, too!
    To just get the names:

    public static string[] PropertiesFromType(object atype)
        {
            if (atype == null) return new string[] {};
            Type t = atype.GetType();
            PropertyInfo[] props = t.GetProperties();
            List<string> propNames = new List<string>();
            foreach (PropertyInfo prp in props)
            {
                propNames.Add(prp.Name);
            }
            return propNames.ToArray();
        }
    

    And it's just about the same for just the values, or you can use:

     GetDictionaryFromType().Keys
     // or
     GetDictionaryFromType().Values
    

    But that's a bit slower, I would imagine.

    Marc Gravell : ... but atype.GetProperty(prp.Name) is going to return prp?
    Lucas Jones : Oh - you're right! D'oh.
    Lucas Jones : I've fixed that now.
  • You could use the System.Reflection namespace with the Type.GetProperties() mehod:

    PropertyInfo[] propertyInfos;
    propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public|BindingFlags.Static);
    

how to extract a portion of a string in php

I am using preg_replace() for some string replacement.

$str = "<aa>Let's find the stuff qwe in between <id>12345</id> these two previous brackets</h>";

$do = preg_match("/qwe(.*)12345/", $str, $matches);

which is working just fine and gives the following result

$match[0]=qwe in between 12345
$match[1]=in between 

but I am using same logic to extract from the following string.

<text>
  <src><![CDATA[<TEXTFORMAT LEADING="2"><P ALIGN="LEFT"><FONT FACE="Arial" SIZE="36" COLOR="#999999" LETTERSPACING="0" KERNING="0">r1 text 1  </FONT></P></TEXTFORMAT>]]></src>
  <width>45%</width>
  <height>12%</height>
  <left>30.416666666666668%</left>
  <top>3.0416666666666665%</top>
  <begin>2s</begin>
  <dur>10s</dur>
  <transIn>fadeIn</transIn>
  <transOut>fadeOut</transOut>
  <id>E2159292994B083ACA7ABC7799BBEF3F7198FFA2</id>
</text>

I want to extract the string from

r1text1

to

</id>

The Regular expression I currently Have is:

preg_match('/r1text1(.*)</id\>/', $metadata], $matches);

where $metadata is the above string..

$matches does not return anything.... For some reason...how do i do it? Thanks in advance

From stackoverflow
  • you probably need to parse your string/file and extract the value between the FONT tag. Then insert the value into the id tag

    Try googling for php parsing.

  • If you want to extract the text, you will probably want to use preg_match. The following might work:

    preg_match('#\<P[^\>]*\>\<FONT[^\>]*\>(.*\</id\>)#', $string, $matches)
    

    Whatever gets matched in the parantheses can be found later in the $matches array. In this case everything between a <P> tag followed by a <FONT> tag and </id>, including the latter.

    Above regex is untested but might give you a general idea of how to do it. Adapt if your needs are a bit different :)

    Joey : If you use / as the character to delimit your regex (as you have done in your edit) you need to escape any literal / with \/ (such as the one in . That's why I used # :)
    Joey : And sure you can just get from to but that wasn't what you wanted in your question. The best way would probably be to just let PHP parse the XML (there are XML parsers somewhere) and then examine the DOM. Parsing XML with regular expressions is really a PITA.
  • try this

    preg_match('/r1text1(.*)<\/id\>/', $metadata], $matches);
    

    You are using / as the pattern delimiter but your content has / in . You can use \ as the escape character.

  • In the sample you have "r1 text 1 ", yet your regular expression has "r1text1". The regular expression doesn't match because there are spaces in the string you are trying to match it against. You should include the spaces in the regular expression.

  • Even if don't know why you would match the regex on a incomplete XML fragment (starting within a <![CDATA[ and ending right before the closing XML tag </id>, you do have three obvious problems with your regex:

    1. As Amri said: you have to escape the / character in the closing XML tag because you use / as the pattern delimiter. By the way, you don't have to escape the > character. That gives you: '/r1text1(.*)<\/id>/' Alternatively you can change the pattern delimiter to # for example: '#r1text1(.*)</id>#' (I will use the first pattern to further develop the expression).

    2. As Rich Adams already said: the text in your example data is "r1_text_1" (_ is a space character) but you match against '/r1text1(.*)<\/id>/'. You have to include the spaces in your regex or allow for a uncertain number of spaces, such as '/r1(?:\s*)text(?:\s*)1(.*)<\/id>/' (the ?: is the syntax for non-capturing subpatterns)

    3. The . (dot) in your regex does not match newlines by default. You have to add the s (PCRE_DOTALL) pattern modifier to let the . (dot) match against newlines as well: '/r1(?:\s*)text(?:\s*)1(.*)<\/id>/s'

mini laptop development tools recomendations

I have Acer 1 mini laptop that I use on the road. What development tools (ide's, frameworks) are recommended so it will be still light? I'm programming mainly in Java and C++, with XP installed.

From stackoverflow
  • Well Visual Studio is out of question :).

    You could use some light editor like Notepad++ and a command line compiler.

    Dylan Bennett : I have Visual Studio C# Express edition running on this Dell Mini with the MSDN 2008 library installed. So Visual Studio is most definitely not out of the question. It works just fine for me. I also run Eclipse too, and though it's slow to start up, it works quite well after that.
    Bojan Milenkoski : I was kidding about Visual Studio, but not much. I suppose you have an external hard drive or the internal one is not a 4GB (8GB) solid state drive. These laptops are not intended for real development. And then again you could bring an extra monitor, keyboard, mouse, solar charger, beer cooler...
  • try JCode for java

    and CodeLite for C++

  • Code::Blocks is a pretty nice C++ IDE for a low resolution screen. (ref)

  • here is something interesting...

    Maybe you can run the big guns.. provided it runs on linux that is

  • I use SciTE and the command line (ant, make) on my netbook.

  • In similar situations the first thing I load up is JEdit. It's plugins cover virtually every language you've ever seen and functionality you'll ever need. It's an extremely useful tool to be familiar with just because it means you need only the one tool across multiple platforms and development tasks and for that reason I'd strongly recommend it over more focused programs.

    jEdit is a mature programmer's text editor with hundreds (counting the time developing plugins) of person-years of development behind it.

    Some of jEdit's features include:
    * Written in Java, so it runs on Mac OS X, OS/2, Unix, VMS and Windows.
    * Built-in macro language; extensible plugin architecture.
    * Dozens of macros and plugins available.
    * Plugins can be downloaded and installed from within jEdit using the "plugin manager" feature.
    * Auto indent, and syntax highlighting for more than 130 languages.
    * Supports a large number of character encodings including UTF8 and Unicode.
    * Folding for selectively hiding regions of text. Word wrap.
    * Highly configurable and customizable.
    * Every other feature, both basic and advanced, you would expect to find in a text editor.

    Cruachan : some clue as to the -1 on this would be helpful - i see no reason why it's not relevant or appropriate
  • Vi / vim. I take it Ctrl+Alt+F1 still works on Linpus/Xandros/UNR?

    I'm not joking here (:-) It has decent syntax highlighting support. And it has that cool :make thing. :)
    For example, in C++, you can do:

    :make
    

    and it will do a very IDE-ish thing (kinda similar to Turbo C now that I think about it) - pop up a list of errors you can cycle through. Also, you could (I suppose):

    :!javac hello.class
    

    To compile your Java programs (w/out the error box though). Also, it's support for splitting itself into boxes is very flexible - I hate VS's method now.

  • Emacs is a very powerful editor which you can use to do all your Java and C++ coding. With an extension like Emacs Code Browser, you'll be good to go.

    I would have normally mentioned Eclipse, which I still this is not as heavy as people talk it up to be, but I'll leave that for you to decide.

  • I find Process Explorer to be very helpful for judging how "light" a tool is.

  • I have a lot of class mates with similar laptops (Eee PC etc). They all seem to use Eclipse for Java development. With CDT (http://www.eclipse.org/cdt/) you could use that for C++ as well.

Is it good to use printStackTrace() in swing program?

Hi, I'm developing a small swing application, and I'm not sure if I should use the printStackTrace().

If I get an exception I show a user via JOptionPane a message, e.g: file not found etc.

But at the same time, I'm using the printStackTrace(), I wasn't sure about neither showing the stack trace to a user nor not to print anything...just in case it would be needed.

Can I leave the printStackTrace there or why not to?

thank you for advice.

From stackoverflow
  • Log stack traces to a log file they wont mean anything to the end user anyway

    Print meaningful error messages to users. i.e File not found etc

    feiroox : where I should place the file?
    Paul Whelan : I tend to log to /var/log/applicationname on linux systems. you can configure this via a properties file. So you don't need to harcode anything in your application. As Vinegar suggested using something like log4j or Java Logger http://java.sun.com/j2se/1.4.2/docs/api/java/util/logging/Logger.html
    feiroox : yes but that's the problem with files. /var/log/ doesn't have to be in windows and elsewhere.
    Adeel Ansari : Have a look at the configuration part of the manual. http://logging.apache.org/log4j/1.2/manual.html
    Paul Whelan : You could if you wanted pass the logging location as a command line argument, default to the temp directory System.getProperty("java.io.tmpdir");
  • printStackTrace() contains information relevant only for the developer so it is a good practice to avoid to expose them to the user

  • A better idea is to replace those with the use of any Logging API, like Log4J. And of course, as Paul mentioned, show the user meaningful error messages where ever appropriate.

  • I agree that a logging framework is a good idea for any decently sized program. That being said most users are pretty comfortable with sending in a screen shot of any errors, so, from a support perspective, it can make life easier to include (a few) extra details in any error screens.

    Adeel Ansari : Here we have an automatic email feature which works like charm in sending the immediate error. But its safe to dump all in log files.

pthread returns 251

pthread_create returns the value 251 without creating the thread. Does anyone know what the problem is? Please help. The machine is a HP-UX.

I'm new to multi-threading.

   #include <stdio.h>
   #include <stdlib.h>
   #include <pthread.h>

   void *print_message_function( void *ptr );

   main()
   {
        pthread_t thread1, thread2;
        char *message1 = "Thread 1";
        char *message2 = "Thread 2";
        int  iret1, iret2;
        /* Create independent threads each of which will
         * execute function */

        iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
        iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);

        /* Wait till threads are complete before
         * main continues. Unless we  */
        /* wait we run the risk of executing an
         * exit which will terminate   */
        /* the process and all threads before the
         * threads have completed.   */

        pthread_join( thread1, NULL);
        pthread_join( thread2, NULL);
        printf("Thread 1 returns: %d\n",iret1);
        printf("Thread 2 returns: %d\n",iret2);
        exit(0);
   }

   void *print_message_function( void *ptr )
   {
        char *message;
        message = (char *) ptr;
        printf("%s \n", message);
   }
From stackoverflow
  • Edit : On HP-UX11. pthread_create is failing with error 251: Function is not available.

    Check whether -lc comes before -lpthread in your link order. If this is the case, then the call would resolve to stub in C-library and could cause this error.


    Did you link with -lpthread?

    You should use errno.h to see what error 251 is on your system or this should give you a more detailled message :

    printf("%s\n", strerror(errno));
    

    Moreover, when using pthread, you should check for the return value of almost every call to pthread* (see the man of every function to check for possible error returned)

    For pthread_create, you have at least 2 possible errors (depending on your system and pthread implementation) :

    pthread_create() will fail if:

    [EAGAIN] The system lacked the necessary resources to create another thread, or the system-imposed limit on the total number of threads in a process [PTHREAD_THREADS_MAX] would be exceeded.

    [EINVAL] The value specified by attr is invalid.

  • This compiles and runs on my Linux box with the following result:

    Thread 1
    Thread 2
    Thread 1 returns: 0
    Thread 2 returns: 0
    

    So it looks like the problem is not in your code, but something in the environment. I haven't used HP-UX for over 10 years, so I can't help you there.

    Shree : Yes, looks like it's got something to do with the environment.
    claferri : seems it could be the link order, check my edited answer.

NETCFv35.Messages.EN.wm.cab?

In the .NET Compact Framework 3.5 exceptions by default don't have their actual error message string installed. Great for cramming the compact framework into windows mobile devices with less memory, but not so great when you're a developer and something goes wrong on the device.

From the default placeholder message I know there is a CAB available to install these messages in case room is available and they are needed. I have already installed NETCFv35.Messages.EN.wm.cab on my phone. However, I still get the following Exception.Message for every exception thrown:

"Er is een foutmelding beschikbaar voor deze uitzondering, maar deze kan niet worden weergegeven omdat deze berichten optioneel zijn, en momenteel niet zijn geïnstalleerd op dit apparaat. Installeer NETCFv35.Messages.EN.wm.cab voor Windows Mobile 5.0 en hoger of NETCFv35.Messages.EN.cab voor andere platforms. Start de toepassing opnieuw om het bericht weer te geven."

Even if you don't read Dutch, the general meaning of the message should be clear enough. Funny thing is that, even though both my Vista VS2008 developement laptop is in English and my HTC TyTN II (development) mobile phone has a standard WM6 UK ROM on it, this message is in Dutch. (?)

I would really appreciate if anyone has answers to any of the following questions:

  • Is the Dutch message perhaps coming from the NETCFv35 itself? It was not in the TyTN II WM6 ROM, either VS2008 or I myself must have installed it. Is there even a localization of the framework itself?
  • Is the Dutch message perhaps coming from the NETCFv35.Messages.EN.wm.cab I installed after seeing the message for the first time? Even though it has "EN" in its name?
  • And how would I know?
  • Running the application in a blank WM6 Professional emulator lets VS2008 install the NETCFv35 on it and there I get exception messages in English.
  • Bottom line: Who has any idea what I would have to do to get actual Exception.Message texts from my phone? Either Dutch or English is fine. ;-)
From stackoverflow
  • What about your regional settings?

    peSHIr : You mean that NETCFv35.Messages.EN.wm.cab might really include English messages and a default one for each of the other locales, which would give me the generic Dutch one on my phone? (Which is set to Dutch in regional settings to get date/time/currency format right.)
    peSHIr : Will have to check whether anything changes with the exception message when I set the regional settings to something in English. Thanks for the suggestion, will get back to you on this.
    Konstantinos : yes, i was suggesting to check the regional settings of your PDA and see whether its dutch or english
  • Have you tried what is proposed here? It is an MSDN blog post about fixing exception messages on the .NET Compact Framework 3.5.

    peSHIr : I hadn't seen this blog post yet, but it seems to describe the problem (and a possible solution) perfectly. Still have to try it out - original reason for wanting to know a particular exception message is gone now - but this seems to be the answer I was looking for.

visual studio 2008 installation

I cleared windows temp file and %temp% from my system . (i installed vs 2008) but now i can't able to create new project (window application), whether VS 2008 installation file is related to temp. The error showing that doc settings/temp/ .... some file missing........

From stackoverflow
  • Hi,

    not quite sure if you are actually missing the project templates or if the project templates themselves are failing, but if it's the former, then try

    Open cmd.exe, goto \Common7\IDE. Run "devenv /installvstemplates"

    Also see here: http://msdn.microsoft.com/en-us/library/ms247116(VS.80).aspx

    HTH Alex

Missing dependencies when building through CruiseControl

The problem is that when projects are been built and produced normally without any errors the final packaged msi is missing dependency assemblies that are normally packaged if someone builds the project through visual studio for example. So what happens is that the application is getting installed normally and then crashes on run time by saying that xyz dll is missing.

From what i can tell it either doesn't refresh the dependencies before building the setup project or somehow fails to include all of them.

We build by using devenv and the solution file (Rebuild all)

Has anyone encountered something similar and if yes how did you resolved it?

edit: CruiseControl is running in a different maching that the development one. Moreover we have figured out that this happens with projects referenced within a solution.

IE in a solution with 3 projects, A a library, B an application that references A and C a setup project then after the build what happens is that B is missing A although the build is successfull and the msi produced.

From stackoverflow
  • There's another post with what looks like the same question, but I haven't been able to check if it works yet. You should be able to include an execution task to run the macro created to refresh the dependencies.

    http://stackoverflow.com/questions/45593?sort=votes#sort-top

  • When you say it builds fine through Visual Studio by hand, do you mean on the same machine? If so then it probably is the fact that your cruisecontrol service is running as a different user, and as such, has differnt paths and environment variables set, maybe it does not have permissions to access the file system these dependencies are on. If you mean it runs fine on a different machine, then I would make sure that those dependencies actually there and that the user the service runs as has permissions to get to them. We have never encountered these issues, sorry, so I am just trying to guess at a few potential setting up CC.NET issues.

  • You might check to see if the missing dlls are in the GAC on the build machine.

    I ran into an issue a few months back where the build server was generating an install with one fewer dll than any of the developer boxes. It turns out the missing dll was in the GAC on the build box. For some unknown reason, VS2005 decided it didn't need to include the dll since it was in the GAC - even if we specifically referenced a local copy of the dll in the project.

  • This situation is a result of MSBUILD not supporting setup projects. So we are forced to use devenv to build the solution with Cruise Control.

    The real problem was that projects in the same solution were referenced by the main application and while this was not reproducible in full .NET setup projects it did happened repeatedly in CF setup projects.

    We resolved this issue by changing the architecture of our CF solutions to have all related projects in 1 project as folders so there is only 1 exe produced and packaged with the setup project.

    It's notable that we didn't had missing assemblies when referencing other dll files but only when we were referencing library projects which existed in the same solution.

    After googling about this subject i found out some disturbing details about this subject, which point me to the fact that this bug and the incapability of msbuild to support setup project exist since ~2005 in msdn forum reports and not only.

JSONP and invalid label

Using mootools and JsonP I get "invalid label" error in Firefox Error console

JsonP seems to work (I get the data correctly)

{"jsondata":[{"title":"title1","link":"http://xxxx.xxx.xxx","thumbsrc":"http://xxxx.xxx.xxx/17_t.jpg" ,"description":".......","pubDate":"2009-03-09 06:26:00",},{"title":"title2","link":"http://xxxx.xxx.xxx","thumbsrc":"http://xxxx.xxx.xxx/16_t.jpg" ,"description":".......","pubDate":"2009-03-09 06:08:09",}]}

but I get the Invalid label error on "jsondata"

the same file works good with request.json

From stackoverflow
  • This could be due to the extra commas after the dates

  • Putting it in here:

    http://json.parser.online.fr/

    Shows that its valid, but has the extra comma (which will bork IE, although FF should handle it). If removing the comma doesn't fix it, you'll need to post more of your code to help us find the error.

  • comma removed... nothing

    this is the code I'm using

    window.addEvent('domready', function() {

    var gallery = $('gallery'); 
    
    new JsonP('http://myjsoncodeurl',{
      onComplete: function(jsonObj) {
       addImages(jsonObj.jsondata);
      }
     }).request();
    
    var addImages = function(images) {
     images.each(function(image) {
      var el = new Element('div', {'class': 'item'});
      var name = new Element('h3').inject(el);
      var a1 = new Element('a', {'href': image.link,'html': image.title}).inject(name);      
      var desc = new Element('span', {'html': image.description}).inject(name, 'after');
      var a2 = new Element('a', {'href': image.link}).inject(desc,'after');    
      var img = new Element('img', {'src': image.thumbsrc}).inject(a2);
      el.inject(gallery);
     });
    };
    

    });

    it works with normal request.Json, but JSONP that doesn't like my code :(

  • the same file works good with request.json

    With JSONP, your response should be returning a JavaScript function call (i.e. callback) with the JSON data passed in as the argument. If your response is a plain old JSON text, it won't work in the context of JSONP. You have to tailor your backend to accept a callback argument and call that callback with the JSON data.

Vim: how to use variables in vimrc?

Hello,

here what I am trying to do, a simple function to increment a global variable. It works fine.

let g:high_ind = 1

fun! IncHighlightInd()
  let g:high_ind = (g:high_ind + 1) %10
  return g:high_ind
endf

I want to use this variable in a map

map <C-h> :call IncHighlightInd() <CR> :Highlight g:high_ind <CR>

But g:high_ind is not recognized as a variable. How to use this variable?

Or more interesting, is it possible to do something like:

map <C-h> :Highlight IncHighlightInd() <CR>
From stackoverflow
  • You have to use :exe or c_CTRL-R_=:

    nnoremap <c-h> :exe ":Highlight ".IncHighLightInd()<cr>
    nnoremap <c-h> :Highlight <c-r>=IncHighLightInd()<cr><cr>
    

    BTW, I suspect you should have a look at this page: Highlight multiple words on vim.wikia.

Persist java.util.Properties as serialized object using JDO/DataNucleus

The Google AppEngine docs say that I can persist serializable objects using JDO like so

import javax.jdo.annotations.Persistent;
import DownloadableFile;

// ...
@Persistent(serialized = "true")
private DownloadableFile file;

but if I use it with Properties

@Persistent(serialized="true")
private Properties initProps;

I get

DataNucleus Enhancer (version 1.1.0) : Enhancement of classes

Field "initProps" in class "ServletRegistration" has been defined as a Map but the key type is not specified!

Can I fix that with additional annotations?

From stackoverflow
  • Add @Key(types=String.class) @Value(types=String.class)

    since "Properties" is a bit of a hack in that it can also contain non-String, and doesn't allow generic specification so you need to restrict it. The next version of AppEngine will have a version of DataNucleus that doesn't require this additional info.

Strange behaviour when accessing Oracle 8i table from servlet

Hi there,

First a little background, I'm using jdk 1.6. I've got a 2 column table in an Oracle 8i DB that holds a very simple code to word map. There are no strange characters. Both columns are varchar.

From my desktop machine, when I execute the the following:

        OracleDataSource ods = new OracleDataSource();

        ods.setDriverType("thin");
        ods.setServerName("DBserver.db");
        ods.setDatabaseName("DB");
        ods.setPortNumber(1527);
        ods.setUser("user");
        ods.setPassword("password");

        Connection connection = ods.getConnection();
        Statement stmt = connection.createStatement();
        ResultSet res = stmt.executeQuery(SQL);

        CachedRowSet crs = new CachedRowSetImpl();
        crs.populate(res);
        while (crs.next()) {
            System.out.println("ID: " + crs.getString(1) +
                               ",  Name: " + crs.getString(2));
        }

Everything works fine, and I get the results I expect (both return values for getString(1) and getString(2) are exactly as they are stored in the table)

HOWEVER:

When I execute the same exact code in a servlet sitting on a Tomcat server (I'm using a simple applet servlet model to access the table and return a response to the applet), crs.getString(int) returns strings like: 0x53, 0x54, 0x4E and so on.

I am unsure what this means, and would be grateful for any assistance. I am wondering where to start to troubleshoot the problem.

From stackoverflow
  • Oracle 8i is very old. I believe 1999 or 2000. Is your combination of jdk and Tomcat and Oracle and JDBC certified/supported?

    Pol : It would seem you're correct. Changing to Oracle 9i worked like a charm. My guess, the mix of jdk, tomcat and oracle wasn't a good one. Thanks!

How to determine if a file will be logically moved or physically moved.

The facts:

When a file is moved, there's two possibilities:

  1. The source and destination file are on the same partition and only the file system index is updated
  2. The source and destination are on two different file system and the file need to be moved byte per byte. (aka copy on move)

The question:

How can I determine if a file will be either logically or physically moved ?

I'm transferring large files (700+ megs) and would adopt a different behaviors for each situation.


Edit:

I've already coded a moving file dialog with a worker thread that perform the blocking io call to copy the file a meg at a time. It provide information to the user like rough estimate of the remaining time and transfer rate.

The problem is: how do I know if the file can be moved logically before trying to move it physically ?

From stackoverflow
  • On Linux or other *nices, call stat() on the source and destination directories and compare their st_dev values. If they are the same, a logical move can be performed, otherwise a physical copy+delete must be performed.

    On Windows, you can call GetFileInformationByHandle() on handles to the two directories and compare their dwVolumeSerialNumber values. Note that this requires Windows 2000 or later.

    I see you're using Java -- there must be some portal through which you can access this OS-level info (perhaps JNI?)

    Frederic Morin : Wow, impressive :) I'll try to find more information about that. Thank you !
    j_random_hacker : I hope it helps, but I can't guarantee that these conditions will hold -- it just makes sense that they would ;)
    Frederic Morin : Oh, I see. I'm currently looking toward JNA (https://jna.dev.java.net/) for kernel32 and unix API access.
    Frederic Morin : Is it ok for you if I accept my own answer ?
    j_random_hacker : @Blade: By all means, it's the answer that worked for you! :)
  • Ok I'm on something :)

    Using JNA I am able to call the Win32 API (and *nix API too) from java.

    I tried calling GetFileInformationByHandle and did got a result BUT the dwVolumeSerialNumber attribute always equals 0 (tried with my C: and D: drive)

    Then I saw this function on MSDN: MoveFileEx. When the flag parametter is set to 0, the copy on move feature will be disable. AND IT WORKS !!!!

    So I will simply call

    if (!Kernel32.INSTANCE.MoveFileEx(source.getAbsolutePath(), destination.getAbsolutePath(), 0)) {
        System.out.println("logical move failed");
    }
    

    Here is the code to put in the Kernel32.java interface (this file can be found in the src.zip package in the download section of the JNA site):

    boolean MoveFileEx(String lpExistingFileName, String lpNewFileName, int dwFlags);
    
    int MOVEFILE_REPLACE_EXISTING = 0x01;
    int MOVEFILE_COPY_ALLOWED = 0x02;
    int MOVEFILE_CREATE_HARDLINK = 0x04;
    int MOVEFILE_WRITE_THROUGH = 0x08;
    int MOVEFILE_DELAY_UNTIL_REBOOT = 0x10;
    int MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x20;
    
    j_random_hacker : +1, MoveFileEx() is a good find. I'm curious though: how are you getting the HANDLE value to call GetFileInformationByHandle() with? The dwVolumeSerialNumber entry is populated sensibly in my C++ test program (i.e. it's a nonzero value, different for different drives).
    Frederic Morin : I got it using CreateFile wich return a file handle. When you call CreateFile, you have to specify that a new file must not be created so it will fail if the file does not exist.
    j_random_hacker : Hmm... CreateFile() is the right way to get a HANDLE, but I'm a bit puzzled as to why you talked about specifying that a new file must not be created -- are you possibly trying to open the destination *file* (which doesn't exist yet), instead of the destination *directory*?
    Frederic Morin : Actually, I was comparing two files on two differents disks so for my little test, I didin't want to create a new file. But you're right, in the case we are interested in, it would make sense to create the target file at this stage.