Saturday, February 19, 2011

invalid QName when transforming a .net XSLTransform

I have a piece of XML that is structured similar to this:

<root>
     <score name="Exam 1"><value>76</value></score>
     <score name="Exam 2"><value>87</value</score>
</root>

and I would like to transform it to look like this:

<root>
     <Exam 1>76</Exam 1>
     <Exam 2>87</Exam 2>
</root>

Following this article I am using this stylesheet:

 <stylesheet>
  <xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
   <xsl:template match='@*|node()'>
    <xsl:copy>
     <xsl:apply-templates select='@*|node()'/>
    </xsl:copy>
   </xsl:template>
   <xsl:template match='score'>
    <xsl:element name='{@name}'>
     <xsl:apply-templates/>
    </xsl:element>
   </xsl:template>
  </xsl:stylesheet>
 </stylesheet>

However, when I transform it and load it into a document, I receive this error:

System.Xml.Xslt.XsltException: 'Exam 1' is an invalid QName

It seems that many of the google results show people with this error have passed an empty string somehow, the error is "" is an invalid QName, but that's not the case here.

What is the problem? Is there a better, alternative solution?

From stackoverflow
  • You cannot have a space in an element name.

    pc1oad1etter : Yep, that was it.

differences between 2 JUnit Assert classes

Hi,

I've noticed that the JUnit framework contains 2 Assert classes (in different packages, obviously) and the methods on each appear to be very similar. Can anybody explain why this is?

The classes I'm referring to are: junit.framework.Assert and org.junit.Assert.

Cheers, Don

From stackoverflow
  • I believe they are refactoring from junit.framework to org.junit and junit.framework.Assert is maintained for backwards compatibility.

  • The old method (of Junit 3) was to mark the test-classes by extending junit.framework.TestCase. That inherited junit.framework.Assert itself and your test-class gained the ability to call the assert-methods this way.

    Since version 4 of junit the framework uses Annotations for marking tests. So you no longer need to extend TestCase. But that means, the assert-methods aren't available. But you can make a static import of the new Assert-class. That's why all the assert-methods in the new class are static methods. So you can import it this way:

    import static org.junit.Assert.*;
    

    After this static import, you can use this methods without prefix.

    At the redesign they also moved to the new package org.junit, that follows better the normal conventions for package-naming.

  • JUnit 3.X: junit.framework.Assert JUnit 4.X: org.junit.Assert

    Prefer the newest one, especially when running JDK5 and higher with annotation support.

  • I did a rough source code compare and there are no serious changes.

    Lot of comments were added in org.junit.Assert and some refactorings are done.

    The only change is the comparison with Arrays. There are some code clean ups, but there's (imho) no functional change.

  • There is in fact a functional change: org.junit.Assert will complain if you use the two-argument assertEquals() with float or double, while junit.framework.Assert will silently autobox it.

Migrating from one DBMS to another

Does anyone have any experience migrating from one DBMS to another? If you have done this, why did you do it? Features? Cost? Corporate Directive?

At times, I've worked with DBAs who insisted that we not use features specific to a DBMS (for example, CLR Stored Procedures in SQL Server.) The DBAs point is, if we use these features, it will make it more difficult to switch to another DBMS if we have to. But so far, I've never been asked to switch.

From stackoverflow
  • In my opinion its silly not to take advantage of all the features of the db your using. Changing DBMS regardless of how many features you use is going to be difficult. There are minute differences between the systems (like some record Date and some record date and time) that will cause a huge headache to change. There is no such thing of just switching to a new dbms.

    From a business perspective there is a lot of work to be done. Analysis on the new dbs to change to. Figuring out the impact of changing dbs on the new system. Having development change the existing systems, testing the changes etc. The list goes on and on. Making a switch like that on an enterprise system takes months if not years. The last place I worked had to change dbs, and it took us a solid 11 months to do it and about 2 million dollars for consultants, hardware, software, and employee salaries. It's a big deal. If someone is saying not to use features, because that "may" happen someday and it'll be easier to do, Most likely, that person is off their rocker. The extra amount of time and money it will take to convert those features is minuscule compared to everything else (most likely). IMO if it will save time and money now buy using those features, then that is the best course of action.

    We did it because the systems we had running on the old dbms were too big. There was too much data, and we needed something a lot more powerful. Plus, it wasn't supported anymore.

  • Switched many times. Mostly because the "Involuntary Conversion" -- an old product is no longer supported or is no longer suitable.

    • DB2 to Oracle. Pre-UDB data was preserved and moved into Oracle.
    • MS-Access to Oracle. Continued using the Access front-end over Oracle tables.
    • Oracle to Oracle. 6 to 8, I think...

    "why did you do it?" Not features. Not cost. In all cases, something is broken.

    • Old product no longer works. Either an OS upgrade or something else has made the legacy product break.
    • Old product did not scale.

    Switching is rarely something you choose to do. It's forced on you when vendors go out of business (Ingres did this once) or stop supporting your version (Microsoft does this frequently).

    Then, of course, it's a crisis. Compounded by the technical complexity of trigger and stored procedure changes. If it was only the data, it wouldn't be much of a crisis. Dump to some standard form (CSV, for instance), reload, and you're up and running.

    More importantly, the more "stuff" (stored procedures, triggers, etc.) in the database, the more your application software becomes a confusing pile of hard-to-follow (and hard-to-maintain) kludges. There's nothing so frustrating as waiting weeks for someone to track down a stored procedure name. If it was VB code, everyone would have had access to it. But since it was in the database, it became -- paradoxically -- less visible. Code is code and should be kept away from data.

    See Where to put your code - Database vs. Application? for more on this topic.

  • I've been involved in several projects to migrate data from one database to another. In every case, it was the data that was being migrated--not the RDMBS. If an application is working then there's not going to be any pressure to switch databases for the sake of switching. The impetus for the migration is usually because the old system's data is either out-of-date, incompatible, or both, and that affords an opportunity to switch the RDBMS as well.

    The most likely change is to consolidate the reference data (employees, customers, etc) into the existing master database (for consistency and ease-of-use) and then modify all the other tables so that the keys are pointing to the new reference data. This requires schema and corresponding code changes up and down the stack. It's a data migration--not a database migration. And more than likely you'll want to take advantage of the opportunity to add data, or standardize names, or (de)-normalize the tables, etc.

    The upshot is that these projects nearly always have an enormous impact on the data, the schema, and the code, and any work required to--say--translate T-SQL into PL-SQL will be a trivially small part of the project. So if you're paying for a nice RDBMS, use all of it. To do otherwise would be like not using the trunk or the glove compartment of your new car so that it'll be easier to switch cars when you buy a new one.

  • I worked at a company for a number of years, whose product supported either Oracle or SQL Server. We maintained the model in Erwin, and generated schema scripts, triggers and Oracle Packages from it. The packages were used to make the Oracle triggers work similearly to SQL Server ones (with a logical 'inserted' and 'deleted' tables) We kept two sets of Stored Procedure Scripts.

    With that mess under my belt, I would suggest that you can migrate big projects, so long as you can succesfully make your data tier completely seperate from any logic code. If you can do that, then you can implement whatever database features will speed up the application in the data tier, without affecting your core app.

  • One other point (in support of S.Lott). Depending on your development environment your developers may not have an easy time developing or even viewing stored procedures. Splitting your application code between two different sets of development tools and execution environments can get complicated, and it can make it harder to find skilled employees.

    I don't think that's an argument against stored procedures, but it's certainly something to consider when deciding where the code should reside for a given component of your applications.

Oracle: TNS-12532: TNS:invalid argument

Trying to establish a connection between my windows box (2003 server) and the oracle (11g) database.

I'm able to successfully ping the oracle host from the windows box. However tnsping command fails with the error tns-12532 error.

Any ideas to solve this issue?

From stackoverflow
  • From the Oracle Error Messages documentation:

    ORA-12532: TNS:invalid argument

    Cause: An internal function received an invalid parameter.

    Action: Not normally visible to the user. For further details, turn on tracing and reexecute the operation. If error persists, contact Oracle Customer Support.

    Have you followed that path yet?

  • Sorry for the obvious question, but have you confirmed that you can connect to the db from another pc?

Use AppleScript or other Mac OS method to get filename and path of open files

Is there any way to use AppleScript (or something else) to query currently running applications for the filename and path of the current file that they have open? I know some applications show the filename in the window title which is script accessible, but this isn't a solution as not all do, and hardly any show the path. I also know this is complex because not every application is document based.

Any suggestions on how to find the currently opened file/path in running Mac apps would be appreciated. Thank you!

From stackoverflow

Tree library for PHP using left & right ids

I'm looking for a library in PHP that can create a tree structure from a database (or array of values) with left and right ids. For the result when getting values I am only looking for an array so I can create any type of view. For adding and removing, it would be nice if the library did it all. Even if the library is within another library, I don't mind as I'll probably pull it out and integrate it with my own libraries.

Anyone know of anything?

I'm using PHP & MySQL, so it'd be helpful if it used atleast PHP. If it's a different database I can probably convert it, although maybe the same with PHP if it doesn't use too much language specific functionality.

From stackoverflow
  • This approach is called "nested sets"

    http://stackoverflow.com/questions/272010/searching-for-the-best-php-nested-sets-class-pear-class-excluded#272248

    basically there is the NSTree library which doesn't seem to be maintained and there is a PEAR library. Probably there are others but that's just a summary of the other post.

  • ezComponents Tree library has different backends (tie-ins), that you can choose between. The documentation is pretty good as well.

  • I am in the midst of a project that uses tree structures for navigation and also selection of (what to) update. I must admit that (being self-taught) I wasn't that familiar with the left-right values approach and so opted for what I have just discovered via a very helpful article to be called The Adjacency List Model.

    Having thought about it, and now being somewhat more familiar, I still think I'd do the same. With TALM, coding PHP views & updates are easy as you're primarily concerned with the parent relationship of a node.

    Then for display you have jQuery Treeview, which I can't recommend highly enough, and for selections there's jquery-checktree which I'm still in the process of incorporating and so can't vouch for, but looks good.

Render < instead of < in ASP.NET

I'm writing a small page to show the employees in our company. I've written a query to pull the info from our database. Then I'm binding that to a GridView to do the dirty work. Here is the query.

"SELECT tblEmpID.empid AS [Empl ID], tblEmpID.posno AS [Pos #], [name] & ""<br />""  &   [jcn] & ""("" & [jcc] & "")"" AS [Name/Job], [orgno] & "" - "" & [depname] AS Department, tblEmpID.[status] AS Status " & _
        "FROM tblEmpID " & _
        "ORDER BY [orgno] & "" - "" & [depname], tblEmpID.name "

As you can see, I'm trying to include a
inside the SQL so when it renders it will look like:

Name
Job Description

But when it renders it renders as

&lt; and &gt;

Effectively showing the <br /> in the record instead of formatting it like I want.

So how to I make it render like I want? I've already tried escaping the < with \ and that did not work.


EDIT: Thanks gfrizzle. Your answer set me down the right path. Also, thank you NYSystemsAnalyst. Your answer helped me think of a different way to do things in the future. Ultimately, I found a different solution. I put this code in the GridView1_RowDataBound event and it does what I need.

If e.Row.RowType = DataControlRowType.DataRow Then
        Dim cells As TableCellCollection = e.Row.Cells

        For Each cell As TableCell In cells
            cell.Text = Server.HtmlDecode(cell.Text)
        Next
    End If
From stackoverflow
  • If you are doing this for read-only purposes, you may want to consider using the repeater control. Then, you can return those as separate fields, thereby eliminating the HTML from the SQL result set. Then, you can use the ItemTemplate in the control to specify the HTML and exactly how you want the results to appear. You can place them in a table, and use the BR tag. This will look similar to a grid, but give you more control over the layout on the HTML / .aspx side.

  • Try setting HtmlEncode="False" on the column in the GridView. That should stop it from encoding your markup.

When should a UI be updated?

I'm working on an online tool for students in my faculty to calculate their final grade for their degrees, and for a while I've had little problems. Students seem to like using the new UI and I've suffered no criticism for a while. Now, I need to add some functionality to the program, meaning the UI will have to chance slightly, but in some very noticeable places.

After watching the whole New Facebook thing kick off, along with the slating of applications with bad UI here on SO and the Ribbon on MS Office receiving mixed reviews I've wondered to myself whether a UI should ever really be changed if users seem to like it. Should a UI be updated after a number of years to keep users interested/be more efficient? Should features be held back in sake of a clean UI?

From stackoverflow
  • Ideally when you first design your UI you create something flexible enough to add any feature you want in the future. In the real world, this is seldom the case. I would say UI updates should be slow and incremental if at all possible (that was the real problem with the facebook change, one big change all of a sudden), and if not then people should be given plenty of notice of the change, and while you're changing you should be sure to plan for future additions so as to not annoy your user base more often than absolutely necessary.

  • That's a tough one.

    Sometimes changing the UI to accommodate new features can't be avoided, but if you are really concerned about the impact of those changes, you might want to step back and try to re-state your problem. Is there another way to handle the features? Is there a way to lessen the impact on the UI? You might even want to try to re-think the whole UI and do some mock-ups that incorporate your new features as if you are building it for the first time. You don't have to make the change, but the exercise might help you think about the problem in a new way. You may also find that the new UI works better, and if you make it intuitive enough, the change might be welcome. If you were to go down that path, I would try a pilot, get some feedback and be prepared to go back to the old UI if it goes badly.

  • Funny. I'm in that very spot right now. Our web-based system has a UI that was designed around solid usability concepts and the users LOVE it. (over 1000 users and lots and lots of feedback).

    But the marketers hammer me about once a year to make the system "more sexy" because "they can't sell it". Now I maintain that given the user feedback, they are perhaps marketing to the wrong audience if only "sizzle" will win them over, but still...

    I let them loose withing some carefully chosen parameters to redesign the main UI (menu look and feel, logo placement), and if it does not negatively affect the usability, then I make the changes. As I said, it happens about once per year.

    What is interesting is two things.

    1. Because no real usability items get changed, the users still love the system.
    2. Just making subtle changes to the general "look and feel" makes the sales folk deliriously happy.
    3. The users actually respond very positively to the changes as well. They feel as if we're "keeping current" each time we change, but always mention that they LOVE the fact that we don't tamper with the working of the site.

    Cheers,

    -R

Webresource.axd problem between regular and secure domain paths

In our setup there are two different websites in IIS 7 setup that point to the same physical path. One with the binding http://websitename.domain.com/ (virtual root ~ is /)

and the second at https://webserver.domain.com/userid/websitename (so the virtual root ~ is /userid/websitename). We use the second for secure aspects of each website.

This causes a problem with the loading of the Webresources.axd files for generated css, and javascript for the AJAX.net toolkit.

Is there a way to have the path to these generated resource files modified. Or somehow set the virtual root path per application.

From stackoverflow
  • I found one solution, using the Render() method to replace the url paths with the correct one. This forum post has info on this solution. I'll have to modify it to check the Request.Url to see which domain the page request is coming from.

    protected override void Render(HtmlTextWriter writer)
    {
         try
         {                  
              StringBuilder renderedOutput = new StringBuilder();    
              StringWriter strWriter = new StringWriter(renderedOutput);    
              HtmlTextWriter tWriter = new HtmlTextWriter(strWriter);    
              base.Render(tWriter);
    
              //this string is to be searched for src="/" mce_src="/" and replace it with correct src="./" mce_src="./". 
    
              string s = renderedOutput.ToString();
              s = Regex.Replace(s, "(?<=<img[^>]*)(src=\\\"/)", "src=\"./", RegexOptions.IgnoreCase);
              s = Regex.Replace(s, "(?<=<script[^>]*)(src=\\\"/)", "src=\"./", RegexOptions.IgnoreCase);
              s = Regex.Replace(s, "(?<=<a[^>]*)(href=\\\"/)", "href=\"./", RegexOptions.IgnoreCase);
    
              writer.Write(s);
          }
          catch
          {
          }
      }
    }
    

Best practices for web login / authentication?

Writing the code for the user authentication portion of a web site (including account registration, logins, and password resets) is pretty simple, but what do you need to make a really good user authentication setup? For example, I'd consider not storing plaintext passwords to be a bare minimum requirement for a web site, but that piece of advice seems to be largely transmitted by word of mouth, and plenty of sites still fail to follow it.

What is some other good advice or good requirements for the user auth portion of a web site? For example, should usernames be user-selected, or should they be email addresses? Any pitfalls for the user registration portion? (CAPTCHAs are probably worth a whole topic by themselves.) Any pitfalls for the password reset portion? Anything else?

Edit:

Somewhat duplicated here : best-practices-for-login-pages

From stackoverflow
  • On the username topic, it depends on how the username will be used on the site (beyond logging in). If your site is based on user generated content and you display the username with the content, allow the user to pick their own and make sure it is not an email address. Also, if the username will be displayed, I generally provide a bit of a warning on the registration form to let the user know, so they don't use their full name only to be angry later when it is displayed on the site.

    I would recommend checking the availability and validity of a username through some type of Ajax call while the user is on the form. Having the form re-load with the password and password confirmation gone, just to have to think of a new username and re-input the data is a pain.

    Other things to consider would be to enforce min/max lengths and some rules around passwords... don't make it difficult to sign up though. Also, accept special characters in the password. I have a couple of very strong passwords that I like to use and a lot of sites don't let me use them, so my account ends up being less secure than I would have made it on my own.

    CAPTCHA is a good idea, just make sure it isn't super-difficult to figure out, that can be frustrating too.

    There are a lot of things to consider and several options for each, but hopefully this will get you started.

  • Encryption

    There was a question about this yesterday - "Why should I care about hashing passwords anyway?" which covers all the reasons why you should do this.

    Captcha

    I disagree with Ricardo on the captcha point - always require a captcha, even really unpopular sites get targetted by spammers. I have blogs that I set up to test some bits of code that I never linked to from anywhere else that were miraculously found by spammers. When a spammer has flooded your site with zillions of identical posts about viagra you'll regret not taking the extra 20 mins to install a captcha. reCaptcha has some plugins that make installing it pretty simple, AND you get to help them digify books.

    Don't forget that visually impaired users will need an audio captcha.

    Forgot password

    If you have confirmed the user's email address then you can just generate a random new password for them. Make sure to prompt them to change their password immediately though as people will forget randomly generated passwords straight away.

    Emails

    DON'T bother trying to implement complex regex's that cover all possible email addresses. Do a simple check for an @ and then let the user click on a link sent to their email address to verify. This is common practice these days but I still come across people trying to get 'clever' about it.

    Form validation

    As well as your server side validation on the registration form you should have client side validation in the form of AJAX to let the user know as they're filling it out whether their chosen username is taken, whether their password is acceptable, etc. Users can get frustrated by having to re-submit registration forms several times.

    Authentication itself

    It's nice to let people log in with either their username or email address as people are more likely to remember email addresses than usernames, especially if they haven't been to your site in a while.

    If your site needs added security (for example, if you're selling stuff and people can get it just by logging in), request another piece of information. Asking for their zip/postal code is a good idea as it only takes a few extra seconds to type and makes it considerably more difficult to brute force passwords.

  • Please also make sure your login page is secured with SSL, If you don't then the user name and password would be sent over the internet in clear text anyway. The rest of your site doesn't need to protected by SSL if there isn't sensitive info anywhere else.

    Josh Kelley : Failing to encrypt the rest of the site means that an attacker may be able to hijack your session, even if he can't read your password.
  • MSDN ran an article that touches on some of these issues; a copy is available here. Most of the suggestions mirror ideas here; one additional idea off of that article is to "track the traffic through your registration funnel." Track hits to error, warning, and recovery portions of the system to see if you need to make some usability enhancements.

Silverlight Control Template Color Property

I am creating a Control Template for the Button control in Silverlight 2. I started with an empty template and added the visual elements I wanted. The main visual element is just a path (shape) filled with a color. The button control already has a Color property associated with it and I was wondering if it was possible to link the Color property of the button control with the Color property of the path inside my template? It just seems pointless to have a Color property on the Button that actually has no effect on the button.

My actual goal in my application is to have this button available in 4 different colors and the only options I can think of so far are 4 distinct templates or writing a new control that inherits from Button and neither of these solutions seem like they're taking advantage of the idea of Control templating.

From stackoverflow
  • It's possible Silverlight doesn't have it available but you should be able to use templatebinding:

    <Path Fill="{TemplateBinding BackgroundColor}" />
    

    Then you can use

    <Button Background="Blue" />
    <Button Background="Red" />
    <Button Background="Green" />
    <Button Background="Yellow" />
    

    HTH

Why Type.Equals(t1, t2) and not the equality operator?

Why must Type.Equals(t1, t2) be used to determine equivalent types, and not the equality operator (e.g. for VB.NET, t1 = t2)?

It seems inconsistent with other parts of the .NET API.

Example in VB.NET:

If GetType(String) = GetType(String) Then Debug.Print("The same, of course") End If

causes a compile-time error of "Operator '=' is not defined for types 'System.Type' and 'System.Type'."

From stackoverflow
  • Given the way types are loaded, that surprises me. Where did you hear this from?

    The docs for System.Type.Equals(Type) suggest that it's comparing via the UnderlyingSystemType property, but I'm not sure under what circumstances two different Type objects would have the same underlying system type.

    I'd be really interested to see an example where this mattered... my guess is that from anywhere in "user code" they'll be the same thing, but there may be some cunning BCL code where it matters.

  • Looking at the source code in Reflector, I can't see how Type.Equals(t1,t2) would be handled any differently than t1 = t2. (There is actually no Type.Equals; it will actually call Object.Equals).

    In C#, T1 == T2 works just fine.

    Jon Skeet : No, Type does override Equals, as far as I can see... at least in .NET 3.5.
    James Curran : It overrides Type.Equals(Type), but not Equals(Type, Type) which is the one the oper== would be mapped to, hence the relevant one here.
  • According to this, the VB equality operator does a value comparison, not a reference comparison. Using Type.Equals(t1,t2) forces it to do reference comparison. If t1 and t2 are types, I would think that either would work, but I'm a C# guy so what do I know. I'd probably prefer using the is syntax for known classes and IsInstanceOf, if I don't care about exact type match.

    Typeof a Is Boolean
    
    a.GetType().IsAssignableFrom( b.GetType() )
    
    Olmo : IsInstanceOf is not a method from GetType. There's however IsInstanceOfType but takes an object (not a type) as the argument and is meant to be used like this: typeof(int).IsInstanceOfType(3). I thing what you want is IsAssignableFrom that is meant to be used like this: typeof(Animal).IsAssignaleFrom(typeof(Leon)
    tvanfosson : You're probably right -- I think I was originally thinking exact type equality (and simply put in an extra GetType()). AssignableFrom works better for non-exact matching, though.
  • In VB.NET The Is is the language operator used to test type equality. Note that Type.Equals test whether two variable of the same type are pointed to the same object. As shown by the below example.

    Public Class Form1
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim X As New TestObject
            Dim Y As New TestObject
    
            If X Is Y Then MsgBox("The Same 1")
            If Type.Equals(X, Y) Then MsgBox("The Same 2")
    
            X = Y
            If X Is Y Then MsgBox("The Same 3")
    
            If Type.Equals(X, Y) Then MsgBox("The Same 4")
        End Sub
    End Class
    
    Public Class TestObject
        Public Value As Double
    End Class
    

    This was done because the history of the 'equals' operator in the BASIC language. When Objects were introduced in VB4 IS was chosen to test for equality as it was felt that overloading equals would be problematic.

    I suggest searching google and usenet for Paul Vicks comments on why some individual BASIC idioms were ported and why other were not. I believe in this case was to avoid confusion as VB.NET introduced

    ObjectA = ObjectC 'which causes ObjectA to reference the same objects as referenced by ObjectC.

    While in VB6 it was Set ObjectA = ObjectC

    The same reason why when objects were introduced in VB4 IS and Set were used to deal with object instead of overloading equals.

    Ultimately these quirks became part of the the Basic Way of coding.

How can I raise an event from anywhere in my WPF application?

I have a base page, BasePage, that raises an event that displays messages to the user. Works great on all pages derived from BasePage. I want to do the same thing from user controls, but they don't inherit from BasePage.

What I want is a central place that I can call from anywhere and in that code it will raise an event. Where is a good place to put this code:

    public void DisplayMessage(string message)
    {
        RaiseEvent(new MessageNotificationEventArgs(MessageNotificationEvent, message));
    }

so that I can call it from anywhere? RaiseEvent is in the UIElement class, so it needs to go somewhere that is a UIElement.

From stackoverflow

Find all Foreign Key errors with Oracle SET CONSTRAINTS ALL DEFERRED

I am using:

set constraints all deferred;
(lots of deletes and inserts)
commit;

This works as expected. If there are any broken relationships then the commit fails and an error is raised listing ONE of the FKs that it fails on.

The user fixes the offending data and runs again. then hits another FK issue and repeats the process.

What I really want is a list of ALL FKs in one go that would cause the commit to fail.

I can of course write something to check every FK relationship through a select statement (one select per FK), but the beauty of using the deferred session is that this is all handled for me.

From stackoverflow
  • Oracle's Error Mechanism is too primitive to return a collection of all errors that COULD occur. I mean, it's a cool thought but think about what you'd have to do if you wrote the code. Your standard error handling would need to be thwarted. Instead of returning an error as soon as you encounter it, you'd have to continue somehow to see if you could proceed if the first error you caught wasn't an error at all. And even if you did all of this you'd still face he possibility that the row you add that fixes the first error actually causes the second error.

    For example:

    A is the parent of B is the parent of C. I defer and I insert C. I get an error that there's no B record parent. I defer and I add B. Now I get another error that there's no A.

    This is certainly possible and there's no way to tell in advance.

    I think you're looking for the server to do some work that's really your responsibility. At the risk of mod -1, you're using a technique for firing an automatic weapon called "Spray and Pray" -- Fire as many rounds as possible and hope you kill the target. That approach just can't work here. You disable your RI and do a bunch of steps and hope that all the RI works out in the end when the database "grades" your DML.

    I think you have to write the code.

  • First option, you can look into DML error logging. That way you leave your constraints active, then do the inserts, with the erroring rows going into error tables. You can find them there, fix them, re-insert the rows and delete them from the error table.

    The second option is, rather than trying the commit, attempt to re-enable each deferred constraint dynamically, catching the errors. You'd be looking at a PL/SQL procedure that queries ALL_CONSTRAINTS for the deferrable ones, then does an EXECUTE IMMEDIATE to make that constraint immediate. That last bit would be in a block with an exception handler so you can catch the ones that fail, but continue on.

    Personally, I'd go for option (1) as you do get the individual records that fail, plus you don't have to worry about deferrable constraints and remembering to make them immediate again after this script so it doesn't break something later.

    I guess somewhere in memory Oracle must be maintaining a list, at least of constraints that failed if not the actual rows. I'm pretty confident it doesn't rescan the whole set of tables at commit time to check all the constraints.

    GHZ : Thanks. The set of data I'm deleting / inserting has inter-dependencies, so I don't think I can use option (1) as there will be many 'false' errors logged - this set of data is guaranteed to be consistent at commit time. I will try option 2.
  • The set immediate answer worked fine for me.

    Taking the A,B,C example from the other post:

    SQL> create table a (id number primary key);
    
    Table created.
    
    SQL> create table b (id number primary key, a_id number, constraint fk_b_to_a foreign key (a_id) references a deferrable initially immediate);
    
    Table created.
    
    SQL> create table c (id number primary key, b_id number, constraint fk_c_to_b foreign key (b_id) references b deferrable initially immediate);
    
    Table created.
    
    SQL> insert into a values (1);
    
    1 row created.
    
    SQL> insert into b values (1,1);
    
    1 row created.
    
    SQL> insert into c values (1,1);
    
    1 row created.
    
    SQL> commit;
    
    Commit complete.
    

    I have a consistent set of data.. my starting point. Now I start a session to update some of the data - which is what I was trying to describe in my post.

    SQL> set constraints all deferred;
    
    Constraint set.
    
    SQL> delete from a;
    
    1 row deleted.
    
    SQL> delete from b;
    
    1 row deleted.
    
    SQL> insert into b values (10,10);
    
    1 row created.
    
    SQL> set constraint fk_b_to_a immediate;
    set constraint fk_b_to_a immediate
    *
    ERROR at line 1:
    ORA-02291: integrity constraint (GW.FK_B_TO_A) violated - parent key not foun
    
    
    SQL> set constraint fk_c_to_b immediate;
    set constraint fk_c_to_b immediate
    *
    ERROR at line 1:
    ORA-02291: integrity constraint (GW.FK_C_TO_B) violated - parent key not foun
    

    Which tells me about both broken constraints (C to B) and (B to A), without rolling back the transaction. Which is exactly what I wanted.

    Thanks

IE6 + IE7 on a clean XP install

We need to test a website in both IE6 and IE7. We've had bugs appear running on actual windows machines that aren't visible under vmware (?!), so we have an actual windows laptop to do this - but only one. Is it possible to install IE6 and IE7 side-by-side in such a way that they absolutely, positively, behave exactly like they would if there was only one of them? How?

From stackoverflow

CakePHP and Flex - How to keep $this->Auth->user() valid ?

Hey all.... I am having a little bit of difficulty to make the integration between flex and cakephp to work with authentication...

I have an MVC on Flex that comunicates with Users MVC on cakephp. It authenticates and sends me back the logged user, but when I try to access another controller, the value for $this->Auth->user() is allways empty....

The Authentication is not persistent....

The funniest thing is that... If I login first on cakephp (through cakephp view) and then start working on the Flex side, everything works just fine, until the timeout is reached.... Something is being done when I call /users/login through cakephp that does not work when I call the service through flex....

Additional Information: I am using CakeAMF/amfext and Fake to make this integration possible

Any idea ?

From stackoverflow
  • It seems that cookie is the problem....

    When logging from Flex, the cookie with CAKEPHP key to the session is not created....

    The only solution so far is to log from Cake and redirect to Flex...

    It seems that the session is mantained while working on Flex app

control lost focus event when using keyboard shortcut

For both .NET Winforms and Windows Presentation Foundation, if I have a text box that the user has just entered text into, and a button, if the user clicks the button the "LostFocus" event fires before the button click event fires. However if the user uses a keyboard shortcut for the button (e.g. Button's text is "&Button" or "_Button" and user performs Alt+B), then the "LostFocus" event fires after the button click event, which is less useful.

Do you know of reasonable workarounds? We have various things that we want to occur in LostFocus before ButtonClick.

From stackoverflow
  • What would happen if you did this first of all in the button handler? (or perhaps subclass the button and override OnClick to apply this logic "worldwide").

    Button b = (Button) sender;
    b.Focus();
    

    Would that get round the issue?

  • You could try tracking whether or not the lost focus logic has occured before firing the button logic. You shouldn't really have code directly in the handler anyway. You could do something like this:

    public partial class Form1 : Form
        {
            private Boolean _didLostFocusLogic;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void textBox1_Leave(object sender, EventArgs e)
            {
                LostFocusLogic();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                ButtonClickLogic();
            }
    
            private void LostFocusLogic()
            {
                /* Do stuff */
                _didLostFocusLogic = true;
            }
    
            private void ButtonClickLogic()
            {
                if (!_didLostFocusLogic)
                    LostFocusLogic();
    
                _didLostFocusLogic = false; // Reset for next time.
    
                /* Do stuff */
            }
        }
    

Vb6: Selecting a file to later be used via a browse button

Here's my code (note that this was given by a friend):

Private Sub Browse_Click()
   Dim textfile As String
   textfile = Space(255)
   GetFileNameFromBrowseW Me.hWnd, StrPtr(sSave), 255, StrPtr("c:\"), 
      StrPtr("txt"), StrPtr("Apps (*.txt)" + Chr$(0) + "*.txt" + Chr$(0) +
      "All files (*.*)" + Chr$(0) + "*.*" + Chr$(0)), StrPtr("Select File")
      Text1 = Left$(textfile, lstrlen(textfile))
End Sub

Basically later on I edit the text file selected so later I call it just by using textfile in my function. However I get a path not found so I feel like I'm doing something wrong. Thanks in advance.

Edit: All I want to do is select a text file, then later be able to call it and use it.

From stackoverflow
  • Maybe sSave contains a pathname, but textfile contains 255 spaces.

  • Isn't this functionality provided by "Common Dialog Controls" in VB6?

    My VB6 is a little rusty but basic dialog to choose a file is provided already.
    Tools -> Controls -> Microsoft Common Dialog Controls v....

    Also, your call to GetFileNameFromBrowseW doesn't include reference the variable - textfile

  • Replace sSave with textfile. When you later need to refer to the file picked, use Text1 (presumably a VB textbox control so Text1 alone is implicitly calling Text1.Text, .Text being the VB.Textbox's default member).

  • As shahkalpesh mentioned, you can access this functionality simply using a standard COM library.

    In VB6, add the component:

    • Project > Components
    • On the Controls tab, choose Microsoft Common Dialog Control 6.0 (SP6)

    Now on your form, add the new Common Dialog control from the toolbox

    In code, you need:

    CommonDialog.Filter = "Apps (*.txt)|*.txt|All files (*.*)|*.*"
    CommonDialog.DefaultExt = "txt"
    CommonDialog.DialogTitle = "Select File"
    CommonDialog.ShowOpen
    
    'The FileName property gives you the variable you need to use
    MsgBox CommonDialog.FileName
    
  • From here

    I found this code and ran it.

    Private Const VER_PLATFORM_WIN32_NT = 2
    Private Type OSVERSIONINFO
        dwOSVersionInfoSize As Long
        dwMajorVersion As Long
        dwMinorVersion As Long
        dwBuildNumber As Long
        dwPlatformId As Long
        szCSDVersion As String * 128
    End Type
    Private Declare Function GetVersionEx Lib "kernel32" Alias "GetVersionExA" (ByRef lpVersionInformation As OSVERSIONINFO) As Long
    Private Declare Function GetFileNameFromBrowseW Lib "shell32" Alias "#63" (ByVal hwndOwner As Long, ByVal lpstrFile As Long, ByVal nMaxFile As Long, ByVal lpstrInitialDir As Long, ByVal lpstrDefExt As Long, ByVal lpstrFilter As Long, ByVal lpstrTitle As Long) As Long
    Private Declare Function GetFileNameFromBrowseA Lib "shell32" Alias "#63" (ByVal hwndOwner As Long, ByVal lpstrFile As String, ByVal nMaxFile As Long, ByVal lpstrInitialDir As String, ByVal lpstrDefExt As String, ByVal lpstrFilter As String, ByVal lpstrTitle As String) As Long
    Private Sub Form_Load()
        'KPD-Team 2001
        'URL: http://www.allapi.net/
        'E-Mail: KPDTeam@Allapi.net
        Dim sSave As String
        sSave = Space(255)
        'If we're on WinNT, call the unicode version of the function
        If IsWinNT Then
            GetFileNameFromBrowseW Me.hWnd, StrPtr(sSave), 255, StrPtr("c:\"), StrPtr("txt"), StrPtr("Text files (*.txt)" + Chr$(0) + "*.txt" + Chr$(0) + "All files (*.*)" + Chr$(0) + "*.*" + Chr$(0)), StrPtr("The Title")
        'If we're not on WinNT, call the ANSI version of the function
        Else
            GetFileNameFromBrowseA Me.hWnd, sSave, 255, "c:\", "txt", "Text files (*.txt)" + Chr$(0) + "*.txt" + Chr$(0) + "All files (*.*)" + Chr$(0) + "*.*" + Chr$(0), "The Title"
        End If
        'Show the result
        MsgBox sSave
    End Sub
    Public Function IsWinNT() As Boolean
        Dim myOS As OSVERSIONINFO
        myOS.dwOSVersionInfoSize = Len(myOS)
        GetVersionEx myOS
        IsWinNT = (myOS.dwPlatformId = VER_PLATFORM_WIN32_NT)
    End Function
    

    From what I can tell you GetFileName function looks right so my guess the problem is with this

    Text1 = Left$(textfile, lstrlen(textfile))
    

    Use this to check

    MsgBox "(" & Text1 & ")-(" & textfile & ")"
    

    to make sure you are getting the expected result from Left$ and lstrlen

    MarkJ : Might be an idea to suggest using the common dialog at the top of the answer? It would avoid you're answer being downvoted anyway:) It's possible Jackie-Brown is using some VBA environment where you can't use the common dialog, in which case your answer is correct of course.
    RS Conley : A suggestion involving Common dialog OCX is not the minimum thing needed to fix the issue as it introduces a dependency and requires changes to the setup of the program. What I missed is that he is passing sSave instead of textfile. But I showed how to diagnose it and give a known good example.

How to detect the language of a document - in PHP?

The basics have already been answered here. But is there a pre-built PHP lib doing the same as Lingua::Identify from CPAN?

From stackoverflow
  • There's a PEAR package Text_LanguageDetect that I've used before. Get's the job done well enough. I'm not sure of any other libs that are more mature.

  • 1- You could do it yourself (the hard way) - detecting both language and codepage by looking at character and n-gram frequencies. You would need lots of "training" data, but it's doable.

    2- You could run a perl script to do the detection for you(much easier).

Service.Controller Status / Polling

I'm having a problem with a administrative app I'm working on. I'm build an interface for stopping, starting and querying various services across 40 or so servers.

I'm looking at service.controller and have been successful in stopping and starting various services with button events but now I'm trying to figure out a way to return the service status to a text box and query for service status every 10 seconds or so and I feel like I'm hitting a brick wall.

Does anyone have any tips or insight?

Thanks!!

From stackoverflow
  • You can trigger the periodic service check by using a Timer object. You can run your service queries on the Elapsed event.

        private void t_Elapsed(object sender, ElapsedEventArgs e)
        {
            // Check service statuses
        }
    

    As for displaying statuses in a text box, you should be able to use the ToString() method on the service status and display that in a regular text box. Remember that you may or may not be on the GUI thread when reacting to the timer events, so you'll need to invoke yourself on to the main thread.

        private delegate void TextUpdateHandler(string updatedText);
    
        private void UpdateServerStatuses(string statuses)
        {
            if (this.InvokeRequired)
            {
                TextUpdateHandler update = new TextUpdateHandler(this.UpdateServerStatuses);
                this.BeginInvoke(update, statuses);
            }
            else
            {
                // load textbox here
            }
        }
    

SPCrossListQuery fails to bring back results

I am calling SPWeb.GetSiteData(anSpCrossListQuery).

It fails to bring back any results or any errors when I call it with an accidental space at the end of the CAML query <Where></Where> clause.

Anyone have an idea why?

From stackoverflow
  • Because SharePoint is intent on making development painful ;)

    Nat : not quite, it *actually* makes development painful :)
  • SharePoint is very picky with CAML queries and gives very unhelpful and sometimes obscure errors. Obviously in this case, a simple String.Trim() will fix the problem.

    Checking your query very carefully and making sure it is well formed has fixed every problem I've had with this.

How do I get back a 2 digit representation of a number in SQL 2000

I have a table on SQL2000 with a numeric column and I need the select to return a 01, 02, 03...

It currently returns 1,2,3,...10,11...

Thanks.

From stackoverflow
  • Does this work?

    SELECT REPLACE(STR(mycolumn, 2), ' ', '0')
    

    From http://foxtricks.blogspot.com/2007/07/zero-padding-numeric-value-in-transact.html

  • John's answer works and is generalizable to any number of digits, but I would be more comfortable with

    select case when mycolumn between -9 and 9 then '0' + str(mycolumn) else str(mycolumn) end
    
  • where n is a positive integer between 0 and 99:

    select right('0'+ltrim(str(n)),2)
    

    or

    select right(str(100+n),2)
    

    but I like John's answer best. Single point of specification for target width, but I posted these because they are also common idioms that might work better in other situations or languages.

  • This sort of question is about the interface to the database. Really the database should return the data and your application can reformat it if it wants the data in a particular format. You shouldn't do this in the database, but out in the presentation layer.

Video sharing site with embeddable upload control

I'm in the process of building a site with embedded videos. I'd prefer not dealing with the videos myself and instead use something like Vimeo Plus. I also would like the future administrators of the site to be able to upload videos directly from the administration interface of the site (i.e. so that they don't have to go to Vimeo for uploading). Vimeo doesn't appear to have an embeddable upload control. I could upload the videos to my server first, and then transfer it to Vimeo using their API, but a lot of things can go wrong in the process...

Has anyone found a video service with an embeddable upload control, or solved this problem some other way?

UPDATE: Looks like bitsontherun may be an option, or perhaps brightcove. (Neither turn out to have prepackaged upload component).

From stackoverflow
  • I just deployed a site where the administrators can upload videos to the server using FCKEditor's upload functionality hooked into a Drupal site. Security isn't as much of a worry since the capability is locked down by role, and like you say you can do whatever you want with the video file once it's on your server.

  • Brightcove is definitely one way to go. They have full API's that allows you build a component for upload. They also provide a batch ingest process. I know this doesn't solve your embeddable component desire, but this can get on your way to creating one.

Interactive Statistical Analysis tool

I'm looking for a basic software for statistical analysis. Most important is simple and intuitive use, getting started "right out of the box". At least basic operations should be interactive. Free would be a bonus :)

The purpose is analysis of data dumps and logs of various processes.

  • Importing a comma/tab separated file
  • sorting and filtering rows on conditions
  • basic aggregates: count, average, deviation, regression, trend
  • visualization - plotting the data,bin distribution etc.

Excel fails (at least for me) for the filtering and re-combining data, I guess something like "Excel with SQL" would be nice. I've been using MS Access + Excel and copying around data before, but that's a pain.

Do you have any recommendation?

Clarification I am not looking for a specific tool for IIS/web server logs, but various data end event logs (mostly from custom applications) with tab-separated values.

From stackoverflow
  • Specifically for Log file analysis I would recommend Microsoft's Log Parser(free), which will allow you to run queries with basic aggregation against all types of text based files (and across sets of files), XML, CSV, Event Log, the Registry, file system, Active Directory, etc..

    There is also a free GUI build on top of it called Log Parser Lizard GUI which makes it more user friendly and can do basic graphing etc.

    peterchen : That looks like a good start, but I can't get at lizard to accept my columns (first line in a tab separated file) - do oyu know how?
    peterchen : I gave up on the lizard GUI for now, but OMG the Log parser is, like, sooo awesome!!!
  • I used Tableau Software at a previous gig, and it's pretty amazing - extremely intuitive and easy to use.

    Unfortunately it's also pricey.

  • You might find gretl very useful (thanks GNU !!!)

    http://gretl.sourceforge.net/win32/

  • I would consider looking at R, it is:

    • Free
    • Widely used by statisticians
    • Fairly easy to use.
    • Can easily do everything you mention in your post
    Tal Galili : Hi Carlos, Although I love R a lot, I have yet to see a dedicated package in it for log file analysis. Therefore, I am not so sure it will fit the bill... Tal
    Carlos Rendon : @Tal, Why would you need a dedicated package? The whole point of R is to make statistical analysis easy. Just about every R program does the 4 things mentioned by peterchen and R has easy to use, built-in support for all of all of them.
    Tal Galili : Hi Carlos, As I wrote - I really love R, BUT... Log file analysis, in order to allow one to be able to do something in the level of well developed softwares, one need to do a lot of preprocessing (for example - taking out bot i.p's). I have no doubt it can be done in R. But without a package from someone who helped create some framework - I am not sure how much work this might take (again, it well depend on the depth of the analysis which is being employed) Cheers, Tal