Saturday, April 30, 2011

How do I get at the sql statement that caused an SQLException using the Postgres JDBC driver in Java?

Background

In my current project - a server product with no GUI front-end, I'm trying to write in better error handling support. Errors currently are outputted to the logs and are typically not read by users.

We use PostgreSQL as our database backend and we access it using direct JDBC calls and DAOs via a database pooler. Most database related exceptions are wrapped in a generic DatabaseException class that implements RuntimeException and attempts to pull out debugging and state information from the exception it was passed. In our particular case, it will access the underlying PostgreSQL database driver - PSQLException. So far this approach has worked well for getting more verbose information about what caused the database error, with the notable exception described below.

Furthermore, since we have very specific performance and legacy support requirements we have a lot of custom SQL magic that makes the following the stack trace back a bit more time intensive but not impossible or difficult.

Problem Described

I have noticed that when we get a SQLException as a result of a faulty SQL statement, the driver's implementation does not return the SQL statement that caused the error. After doing a little searching, I found out that there is a way to drop the PostgreSQL driver into a debug mode on startup and have it display properties about its internal query. However, it is undesirable for us to run the driver in debug mode in our production environment (and honestly I haven't been able to figure out how to get it into the freakin mode!).

Question

Has anyone else dealt with this same issue before and found a solution? If not, is there some OOP pattern out there for storing query information before execution and then assigning that information to the exception thrown? Or do most developers just feel that they don't need the full query to troubleshoot database issues? Honestly, I don't need it because I have the full stack trace and I can look up the invoking query, but it definitely speeds up my debugging by having it be the first thing that I see in the error logs.

From stackoverflow
  • The stacktrace can point you to the DAO method that caused the problem, isn't that the case?

    Edit after comment: If your SQL query is complex and dynamically generated from previous parts of the code then you could log (level TRACE or DEBUG) these statements before executing them. In the logging configuration you could enable logs only for the DAO(s).

    Elijah : For the case of DAO methods that approach works fairly well. However, in the case of some of our more complex SQL statements invoked via JDBC it is a little more complicated because we get a trace to the execute method and we then have to work are we back to where the statement/prepare was defined.
  • I am assuming that when you make the call to execute the query you have the statement, and you receive the Exception, so at that point you have both. It seems like you could do your analysis there.

    However, maybe you're catching things further up. So, what you might do is on your own custom subclass of Exception, DatabaseException, add a triggeringSQLStatement member with a getter and setter, and then at the place where you attempt to execute the statement, catch the original Exception from PostgreSQL, create a new DatabaseException, set the triggeringSQLStatement to be the statement you just executed, and call initCause() on the DatabaseException to set the Exception caught from PostgreSQL as the cause of your exception; then throw your DatabaseException and the calling code which catches it will have an object that prints out a very decent stack trace of what happened plus provides access to the SQL statement that caused the problem. For more information on this approach, you might want to research Java Exception chaining. Even if you don't use all of what I just described, I think you should definitely be using Java Exception chaining already.

    If there's not a spot anywhere in the code where you have access to both the SQL statement that caused the problem and the Exception that gets thrown, I'd be very curious as to why, and how that is possible. And I'd suggest you redesign your code so that you do have such a spot.

    Edit: Since you're wanting to see the SQL statement first thing in the log, you could probably also override your DatabaseException's toString() method (or other appropriate methods; I'm not sure what gets called when an Exception is printed out) to print out the included SQL statement, assuming you included it as I described above.

  • I used to add the SQL query in my custome Exception object when ever there is an SQLException. In the code where ever I am logging the exception details in log file, I used to log the SQL also.

    Adeel Ansari : Its better to log the parameters as well. +1
  • Why not add a file logger around all JDBC calls (log4j)?

    Whenever you make a SQL call you log the SQL and how long it took to execute. Simple stuff.

    We do this for any call to an external system E.g. SOAP calls, RMI, Corba, etc. Its proved invaluable almost every day and if it affects performance.. I haven't noticed!

    If you have security concerns i.e. don't want it to go to a log file on a client machine, you could use a SocketAppender and send it to a remote machine for centralised logging purposes. This won't be totally secure but would stop the casual snooper.

  • The easiest way to do this I think is to use a third party product like p6spy. It gets in between your jdbc driver and your database and reports the exact queries that are run. It's very easy to run on demand as it's implemented as another JDBC driver that will delegate to your actual JDBC driver. Very powerful tool that I can't imagine working without.

    http://www.p6spy.com/

  • Another solution to spy on the queries you are executing is pgFouine which analyses and reports on the logs generated by Postgres

Is managed code is the only way to use SMO in c++???

I have to work with SQLSERVER SMO in C++. Is Managed code is the only way to work with SQLSERVER SMO in C++ ?

I have tried many ways.. but I found that using managed code is the only option. Are there other ways?

From stackoverflow
  • Technically, you can expose .NET assemblies to standard COM infrastructure, but that requires changes to the source code (see this). You may try and create a COM-aware wrappers around standard SMO objects and then use them as regular COM classes in C++.

Serializing linq entities with WCF

I am serialzing a linq object through WCF. The dbml is setup for unidirectional serialization.

My objects are pretty simple: Budget has a collection of BudgetLineItems. Each BudgetLineItem has an ItemCateogry.

Budget/BudgetLineItems are serialized fine. ItemCateogry on each BudgetLineItem do not, however. I noticed by default, linq didn't add a [DataMember] on ItemCategory for each BudgetLineItem. I added it manually, and also removed any possible circular reference on the ItemCategory entity with [IgnoreDataMember]. Not luck, however.

questions:

  1. Can wcf, by default, serialize many-to-one relationships, or am I just missing something? I know the serialized data would be rather redudant with duplicated ItemCategory data for each BudgetLineItem, but that is fine.

  2. Do I need to do a custom DataContractSerializer for this?

** EDIT ** Actually, that did work (adding [DataMember]), I just didn't update the service reference on the client (duh).

NEW QUESTION: Is there a way to tell the linqtosql designer to maintain those [DataMember] and [IgnoreDataMember] fields on an entity that the designer is generating? otherwise I'll need to update them everytime I save the dbml.

From stackoverflow
  • you shouldn't send linq entities with WCF. Instead make your own business datamodel and send those over the wire. If you ever change your database you don't want to change every program that connects with your service

    ericvg : agreed, but for the purpose of this particlar item, we're trading that off.
  • Wow you successfully serialized your LINQ 2 SQL objects for WCF?

    When I tried this (very reluctantly, see below as to why) it really fell over, there were relationships in my L2S entity pointing to children, and then the child pointing back to the parent and obviously when enumerating for building the WCF object, it could not traverse the tree infinitely in this fashion and [to the best I remember] it resulted in an overflow exception, so what I am basically saying is beware if you go down this road!

    Following up on Michael's post, I would suggest transforming your WCF objects to POCO's (custom model representation). I'm kind glad the above did not work, as I would always prefer to make a custom WCF object which transports a clean subset of data, exactly what the WCF request needs and it then doesn't include a stack of superfluous data to be sent across the data, and I'm sure your L2S entities have lots of it. The actual reason I tried sending my L2S data directly across the wire was because I had to make an engine which employed certain 'rules' these rules were stored in a correlation of about 4 database tables with relationships and it was not viable to upkeep a separate WCF object.

    So in the end what I ended up doing was extending custom code gen classes to include Wcf.cs with [DataContext] and then cloned property for property the L2S classes -> WCF custom classes.

    It worked perfectly in the end and this is the cloning procedure I used with instructions on my blog.

    I am happy with this and don't feel there is bad practice involved. Hope this helps.

    ericvg : Thanks for the info. For successful serialization, we had to add a [DataMemberIgnore] to any prop that was recursive (usually the reference back to the parent), since those won't serialize. That invovled changing the dbml, which of course will be overwritten on every change. It works, but not very seamless. As you know, the serialized objects are _huge_. thankfully, this was only for a proof of concept (SQLRS2008 consuming a WCF layer to our services to rid us of redudant logic)
    GONeale : OK no prob. Well check out my cloning procedure, hopefully that route will help you.

Running multiple SQL statements in the one operation.

I'm trying to use ADO to create several tables at once, into MS Access. Is it possible to do multiple statements in the one operation? For instance:

...
// I have omitted the field details 
CString sQuery = "CREATE TABLE [Table1] (..., PRIMARY KEY ([ID])); \nCREATE TABLE [Table2] (..., PRIMARY KEY ([ID]));";
oRecordset.Open(oDatabase.m_pConnection, sQuery)

This fails due to a "Syntax Error in CREATE TABLE statement", although each of the create statements work on their own perfectly. Is there a way of doing this sort of thing? There will also be statements to add constraints, add indexing, etc., and I'd really like to be able to do it so that I don't have to split up the string into separate parts.

From stackoverflow
  • I don't know if ADO is constructed over JET OleDB Engine, which I suppose, if it is this way, The Jet Engine doesn't support execution of multiple statements in one single batch, we tryed separating with ; and with the GO reserved word, but it does not work.

  • ADO to MS Access does not support batch SQL statements. You need to run each statement as a separate execution.

  • If you're sample set of commands is typical, just do something like this in VBA or the language of your choice:

    public sub ExeuteBatch(BatchString as String)
        var s as string  
        var abatch as array  
        sbatch = replace(sbatch, "\n", "")
        abatch = split(BatchString, ";")
        for each s in abatch
            ** adodb execute s here **
        next s
    end sub
    

    That's off the top of my head, but you should be able to take it from there I hope.

  • I think you can run multiple commands in one ADO Command.

    You just need proper line feeds between then. i.e. \n doesn't work.

    Try something like this: (Using VB Syntaxish)

    MyQuery = "Select * from Whatever " & vbLf
    MyQuery = MyString & "Select * from SomethingElse " & vbLF

    oRecordset.Open(oDatabase.m_pConnection, MyQuery )

    onedaywhen : ADO simply passes the SQL code to the engine and the engine in question (ACE/Jet) has no support for multiple SQL statements).
    GordyII : Ah, that would make sense. Thinking about it, I have done this successfully on SQL Server.
  • People who think you can send multiple SQL statements to Jet in a batch just aren't thinking.

    Jet is a file-server database engine -- there is no centralized server process controlling interaction between clients and the actual data store. Instead, clients are all running individual instances of Jet and cooperatively editing a file in a way that is controlled by the Jet locking file (LDB). Without a centralized process to serialize and prioritize the SQL statements, you wouldn't want Jet to be able to process multiple statements in a batch.

    Those who are offering the suggestion of using ADO and separating the statements with a CrLf should code it up and give it a try and then get back to us about how useful their speculative advice actually is.

  • ADO isn't the issue: the ACE/Jet engine simply does not support multiple SQL statements within a single operation. In other words, ACE/JET SQL lacks procedural syntax found in most 'industrial-strength' SQL products.

    You will need to issue a Connection.Execute for each CREATE TABLE statement i.e. client side procedural code.

Friday, April 29, 2011

href error in .jsp

i had this code in my .jsp file:

<li><a href="${pageContext.request.contextPath}/pages/client_home.jsp" id="home">Home</a></li>
  <li><a href="${pageContext.request.contextPath}/pages/client_about.jsp" id="about">About</a></li>

and when i click the link, i got this error:

HTTP Status 500 -

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: javax.servlet.ServletException: File "/1920.14042009/pages/client_navbar.jsp" not found org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:522) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:398) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:337) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266) javax.servlet.http.HttpServlet.service(HttpServlet.java:803) ...

i also tried replacing ${pageContext.request.contextPath}... with http://localhost:8080/1920.14042009/pages/client_about.jsp.

error still persists.

help pls...

From stackoverflow
  • The problem is not with the two lines of code or using ${pageContext.request.contextPath}

    The file client_navbar.jsp is not available in the context, but is referred by the jsp file that the link points to. Please check...

    bgreen1989 : no, client_navbar.jsp exists..and even if i tried to comment the jsp include of it, error is still exists.
    bgreen1989 : in this project, we've been using .jsp - java servlet - service - dao architechture..

C# subtring parse using regular expression (ATL >> NET)?

What is the C# & .NET Regex Pattern that I need to use to get "bar" out of this url?

http://www.foo.com/bar/123/abc

In ATL regular expressions, the pattern would have been

http://www\.foo\.com/{[a-z]+}/123/abc
From stackoverflow
  • Simply: #http://www\.foo\.com/([a-z]+)/123/abc#

    use parenthesis instead of brackets.

    You will need to use a character on the front and the end of the regular expression to make it work too.

    Nick Berardi : actually this is wrong because the "." is considered any char? So yours also evaluates fine for http://wwwxfood.com/bar/123/abc
    Daniel Brückner : The dot is escaped with a backslash - so it works.
    Nick Berardi : # is not a valid character in ASP.NET, I think you mean ^ and $
    Nick Berardi : Also it wasn't escaped when I posted the comment.
    Erick : @Nick Actually it was excaped but for some reason you have to double escape your text on SO ^_^ , as for the #s don't you need a delimiter usually for your REGEX ... ?
  • Pretty much the same thing

        http://www\.foo\.com/([a-z]+)/123/abc
    
  • This will almost work - just a tiny modification - change brackets to parenthesis.

    http://www\.foo\.com/([a-z]+)/123/abc

    But I consider this regex of not much use because it includes almost the whole string. Would it not be better to match the first path element independently from the whole rest?

    ^http://[^/]*/([^/]*).*$
    Jonathan C Dickinson : Maybe ^http://([^/])*/([^/]*).*$
    Jonathan C Dickinson : Ignore the semicolon, SO added it for some reason.
  • Here is a solution that breaks the url up into component parts; protocol, site and part. The protocol group is not required so you could give the expression 'www.foo.com/bar/123/abc'. The part group can contain multiple sub groups representing the folders and file under the site.

    ^(?<protocol>.+://)?(?<site>[^/]+)/(?:(?<part>[^/]+)/?)*$
    

    You would use the expression as follows to get 'foo'

    string s = Regex.Match(@"http://www.foo.com/bar/123/abc", @"^(?<protocol>.+://)?(?<site>[^/]+)/(?:(?<part>[^/]+)/?)*$").Groups["part"].Captures[0].Value;
    

    The breakdown of the expression results are as follows

    protocol: http://
    site: www.foo.com
    part[0]: bar
    part[1]: 123
    part[2]: abc

Freeing up a TCP/IP port?

netstat -tulnap shows me what ports are in use. How to free up a port, in Linux?

From stackoverflow
  • Kill the process that is listening to the port in question. I believe netstat shows you process ids.

  • I think the only way will be to stop the process which has opened the port.

  • Stop/kill the process attached to it.

  • The "netstat --programs" command will give you the process information, assuming you're root. Then you will have to kill the "offending" process which may well start up again just to annoy you :-).

    What are you actually trying to achieve here? Solutions will vary based on the processes holding those ports.

  • As the others have said, you'll have to kill all processes that are listening on that port. The easiest way to do that would be to use the fuser(1) command. For example, to see all of the processes listening for http requests on port 80 (run as root or use sudo):

    # fuser 80/tcp
    

    If you want to kill them, then just add the -k option.

  • I can write the below code to kill the process kill pidnumber

    But it does not kill immediately it takes 1 minute to release the port. So how to release the port immediately?

    Blank Xavier : I find your question disturbing. It is wrong to be killing processes to get hold of ports. You should be disabling their startup or modifying their config such that they use an alternative port.
    ephemient : Use `setsockopt(..., SOL_SOCKET, SO_REUSEADDR, ...)` if you want to bind to the port as soon as possible.
  • If you really want to kill a process immediately, you send it a KILL signal instead of a TERM signal (the latter a request to stop, the first will take effect immediately without any cleanup). It is easy to do:

    kill -KILL <pid>
    

    Be aware however that depending on the program you are stopping, its state may get badly corrupted when doing so. You normally only want to send a KILL signal when normal termination does not work. I'm wondering what the underlying problem is that you try to solve and whether killing is the right solution.

Auto __repr__ method

I want to have simple representation of any class, like { property = value }, is there auto __repr__?

From stackoverflow
  • Do you mean

    __dict__
    

    ?

  • Yes, you can make a class "AutoRepr" and let all other classes extend it:

    >>> class AutoRepr(object):
    ...     def __repr__(self):
    ...         items = ("%s = %r" % (k, v) for k, v in self.__dict__.items())
    ...         return "<%s: {%s}>" % (self.__class__.__name__, ', '.join(items))
    ... 
    >>> class AnyOtherClass(AutoRepr):
    ...     def __init__(self):
    ...         self.foo = 'foo'
    ...         self.bar = 'bar'
    ...
    >>> repr(AnyOtherClass())
    "<AnyOtherClass: {foo = 'foo', bar = 'bar'}>"
    

    Note that the above code will not act nicely on data structures that (either directly or indirectly) reference themselves. As an alternative, you can define a function that works on any type:

    >>> def autoRepr(obj):
    ...     try:
    ...         items = ("%s = %r" % (k, v) for k, v in obj.__dict__.items())
    ...         return "<%s: {%s}." % (obj.__class__.__name__, ', '.join(items))
    ...     except AttributeError:
    ...         return repr(obj)
    ... 
    >>> class AnyOtherClass(object):
    ...     def __init__(self):
    ...         self.foo = 'foo'
    ...         self.bar = 'bar'
    ...
    >>> autoRepr(AnyOtherClass())
    "<AnyOtherClass: {foo = 'foo', bar = 'bar'}>"
    >>> autoRepr(7)
    '7'
    >>> autoRepr(None)
    'None'
    

    Note that the above function is not defined recursively, on purpose, for the reason mentioned earlier.

    dynback.com : __dict__ is not showing class AnyOtherClass(object): foo = 'hello'

Time Slot SQL Query

I'm trying to write a query to see if an engineer visited his job in a agreed time slot.

Table Screenshot

This is my query so far:

SELECT
  v.[VISITDATE], 
  CONVERT(VARCHAR, v.[STARTTIME], 105) AS 'Startdate', 
  CONVERT(VARCHAR, v.[STARTTIME], 108) AS 'StartTime', 
  CONVERT(VARCHAR, v.[bookeddate], 105) AS 'BookedDate', 
  CONVERT(VARCHAR, t.[starttime], 108) AS 'TimeSlotStart', 
  CONVERT(VARCHAR, t.[endtime], 108) AS 'TimeSlotEnd',
  v.[Status]     
FROM
  [tbl_repair_visit] v 
  INNER JOIN [ltbl_TimeSlots] t ON v.timeslot = t.[Slot]

The 'StartDate' and 'StartTime' is the date and time the engineer went.

'BookedDate' is the date he should have gone, and 'TimeSlotStart' and 'TimeSlotEnd' defines the time span in which he should have started working. So I need a column that is a True/False value to say if he went in the correct time or not.

From stackoverflow
  • SELECT
        CASE
            WHEN StartDate = BookedDate AND StartTime BETWEEN TimeSlotStart and TimeSlotEnd
                THEN 'True'
            ELSE 'False'
        END
    FROM
        ...
    
  • Why not simply:

    WHERE Startdate = BookedDate AND StartTime <= TimeSlotEnd AND StartTime >= TimeSlotStart
    

    ?

How do you organise your MVC controller tests?

I'm looking for tidy suggestions on how people organise their controller tests.

For example, take the "add" functionality of my "Address" controller,

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Add()
{
    var editAddress = new DTOEditAddress();
    editAddress.Address = new Address();
    editAddress.Countries = countryService.GetCountries();

    return View("Add", editAddress);
}

[RequireRole(Role = Role.Write)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Add(FormCollection form)
{
    // save code here
}

I might have a fixture called "when_adding_an_address", however there are two actions i need to test under this title...

I don't want to call both actions in my Act() method in my fixture, so I divide the fixture in half, but then how do I name it?

"When_adding_an_address_GET" and "When_adding_an_address_POST"?

things just seems to be getting messy, quickly.

Also, how do you deal with stateless/setupless assertions for controllers, and how do you arrange these wrt the above? for example:

[Test]
public void the_requesting_user_must_have_write_permissions_to_POST()
{
    Assert.IsTrue(this.SubjectUnderTest.ActionIsProtectedByRole(c => c.Add(null), Role.Write));
}

This is custom code i know, but you should get the idea, it simply checks that a filter attribute is present on the method. The point is it doesnt require any Arrange() or Act().

Any tips welcome!

Thanks

From stackoverflow
  • Well, 13 months later and no answers. Awesome.

    Heres what i do now:

    /tests/controllers/address/add/get.cs
    /tests/controllers/address/add/valid.cs
    /tests/controllers/address/add/invalid.cs
    
  • In my opinion you should forget about naming your tests after the methods you're testing. In fact testing a single method is a strange concept. You should be testing a single thing a client will do with your code. So for example if you can hit add with a POST and a GET you should write two tests like you suggested. If you want to see what happens in a certain exceptional case you should write another test.

    I usually pick names that tell a maintainer what he needs to know in Java:

    @Test public void shouldRedirectToGetWhenPostingToAdd(){
        //...
    }
    

    You can do this in any language and pick any *DD naming convention if you like, but the point is that the test name should convey the expectations and the scenario. You will get very small test this way and I consider this a good thing.

Spring Integration: How does RendezvousChannel work?

I haven't been able to find any examples of how the RendezvousChannel works in Spring Integration. Does anyone know of any resources?

I've read that RendezvousChannel is useful for adapting request/response clients to the asynchronous messaging in Spring Integration.

From stackoverflow
  • RendezvousChannel extends QueueChannel and exhibits the same behaviour:

    • Reading from the channel blocks until either a message is available or a timeout occurs.
    • Writing to the channel blocks until the queue's capacity permits another message or a timeout occurs.

    Internally however, RendezvousChannel uses a capacity of 0 in conjunction with a SynchronousQueue. Therefore, senders will block until receivers have finished, well, receiving and vice versa, basically establishing synchronous communication.

    As for examples, I don't think there are any yet.

    If you want to get an impression of how RendezvousChannel can be used as temporary reply channel for implementing request/reply scenarios (as hinted at in the reference documentation, section 3.2.4), have a look at the source code of the doSendAndReceive method of MessageChannelTemplate. That one uses PollableChannel implementation internally, but the pattern could be easily transfered RendezvousChannel.

How to print dataGridview

Hai How to print All data from datagridview in vb.net. Please Help me. thanks in advance

From stackoverflow

HMACMD5 in .net compact framework

How to implement HMACMD5 algorithm in .net compact framework.

From stackoverflow
  • cfAES supports HMACMD5 and is written for the .NET Compact Framework.

using dataadpter how to update data in database

using dataadpter how to update data in database

From stackoverflow
  • I assume you're talking about SqlDataAdapter. If so, check out

    this

  • myDataAdapter.Update(myDataSet);
    

    A vague question at best merits a vague answer.

How does this regex work and how do i make it repeat only 5 times?

What does this regex do? i know it replaces the filename (but not extension)

    Regex r = new Regex("(?<!\\.[0-9a-z]*)[0-9]");
    return r.Replace(sz, "#");

How do i make it only repeat 5 times? to make it convert "1111111111.000" to "11111#####.000" ?

From stackoverflow
  • Try changing the asterisk after the closing bracket to "{5}" (no quotes). This depends a bit on your regex environment's feature set, but that is a common syntax.

    acidzombie24 : That breaks it (the ext now becomes ###).
  • The regex matches a character (0 to 9) that is not preceded by a dot then any number of 0 to 9 or a to z's.

    The replace line is responsible for the multi replacements. So you want to use the Replace method the has an extra parameter count.

    so the code would look like:

     Regex r = new Regex("(?<!\\.[0-9a-z]*)[0-9]");
     return r.Replace(sz, "#", 5);
    
    Simeon Pilgrim : Not tested, but this should actually replace the first 5 digits, thus giving you '#####1111.000' which is not what you want. So go with Konrad's solution.
  • I havent' tried this but Have tried it, works: how about changing the general pattern to use a positive lookahead instead? That way, it should work:

    [0-9a-z](?=[0-9a-z]{0,4}\.)
    

    Basically, this finds any (alphanumeric) character followed by up to four other alphanumeric characters and a period. This might just work to match the last five characters in front of the period consecutively. It's hellishly inefficient though, and it only works with engines that allow variable-width lookahead patterns.

    Konrad Rudolph : Works for me in .NET.

Is there any way to increase the display speed of the SimpleModal dialog in jQuery?

I am using the SimpleModal plug-in in jQuery.

When I use the action event, the modal dialog appears slowly.

Is there any way to increase the speed of the modal dialog, so it appears quicker?

From stackoverflow
  • Try the onOpen callback described at the modal homepage:

    data.modal({onOpen: function (dialog) {
      dialog.overlay.fadeIn('slow', function () {
        dialog.container.slideDown('slow', function () {
          dialog.data.fadeIn('slow');
        });
      });
    }});
    

    Try using different values for the fadeIn function instead of slow if this changes something.

    venkatachalam : I need Speedup the PopUpMenu Mork,But ur solution is For making slow.Since Appearing Popup menu after click should happen suddenly.not by slow
    Mork0075 : As i said, use different values for the pace. the opposite of is slow should be fast.

Database design for text revisions

This question contains some excellent coverage of how to design a database history/revision scheme for data like numbers or multiple choice fields.

However, there is not much discussion of large text fields, as often found in blog/Q&A/wiki/document type systems.

So, what would be considered good practice for storing the history of a text field in a database based editing system? Is storing it in the database even a good idea?

From stackoverflow
  • I develop a wiki engine and page/article revisions are stored in a database table. Each revision has a sequential revision number, while the "current" revision is marked with -1 (just to avoid NULL).

    Revision text is stored as-is, not diffed or something like that.

    I think that performance is not a problem because you are not likely to access older revisions very frequently.

    dr. evil : I have done the same thing, so far works fine for me. The system is around for 2 years now.
  • Often the most sensible way of tracking the versions of a document is to keep track of the changes made to it. Then, if a particular version is requested it can be rebuilt from the current document and the partial set of changes.

    So if you have a good method of describing the types of changes to a document (this will depend largely on what the document is and how it used) then by all means use a database to track the changes and therefore the versions.

    Dario Solera : Storing only the differences between revisions has the advantage of saving space, but it slows the process of retrieving/rebuilding a specific revision and it also increases the chances of data corruption (what if a revision is lost?).
    CurtainDog : Yes, those are valid points. The optimal approach is somewhere in between and I imagine would be fairly sensitive to the type data I think. In the case of somebody correcting the spelling of a word or two, it seems like overkill to store the entire document again.
    Mocky : @Dario I agree, and upvoted, your answer to this question, but I do not agree with your comment here. Fear of "losing" data from your database is not good reasoning and slowing the process of retrieving a specific revision is less of an issue, as you yourself point out, because you are not likely to access older versions frequently.
  • Given the current state of HDD art, it just does not worth the effort trying to optimize text storage mechanisms: Document (ID, Name) and DocumentRevision (ID, DocumentID, Contents) tables will do the job. the ID in DocumentRevision may also serve as a "repository"-wide revision number. If this is not the behavior you want, assign a separate VersionID to each Document Revision.

How to execute a literal in VBA?

Is there a way to execute a literal such as,

 UseValueKey = ExecuteMethod("Date()")

I want to have the variable UseValueKey return the actual date.

I am using VBA.

Any ideas?

From stackoverflow
  • I haven't done any VBA coding for several years, but I recall that Access VBA had an Eval() method that could be used to evaluate code represented as a string.

    This article gives an example of its usage.

  • You can try the Eval function.

  • Perhaps I'm not exactly following you, but you should be able to use

    Date
    

    for example

    UseValueKey = date
    
  • If, as indicated in the question comments, the function name is known and can be delivered as a method on a class, try looking at

    CallByName object, routine, callType
    

    where callType indicates whether the called routine is a property Get/Let/Set or a Method.

    It feels a lot less kludgey (and somewhat better controlled) than fooling with code evaluation, where you may be leaving yourself open to, er, unexpected consequences...

Software Process using TFS

I'm trying to implement a software process using MSF for CMMI to govern all software pojects in my company using TFS. Is there a reference example you are aware of for a company that went into the same excercise of managing requirements using VSTS along with a 3rd party tool, implement configuration management and change management, define policies for automated builds & CIs, automataed deployment, custom project portals and reports. Is there something that shows a full lifecycle process implementation and practicies through TFS.

From stackoverflow
  • Not a direct answer, but you may want to listen to Radio TFS #18, which covers the topic of different process models and their adoption.

What software can I use to auto generate class diagrams in PHP?

I have some source code and I would like to auto generate class diagrams in PHP. What software can I use to do this?

Duplicate

From stackoverflow
  • Umbrello can do it.

  • Hava a look at Instant Reverse

  • Doxygen can do class diagrams, too (if what I'm thinking of are "class diagrams" :) ).

    monkey_boys : "class daigrams" ??
    Narcissus : Fixed, thanks monkey_boys.

ASP.NET Get Original Text of Label

Is there any way to get the original text from a Asp:Label on a page, after the text has been altered?

with the orginal text i mean the text that is hard coded into the asp.net markup.

From stackoverflow
  • There is no standard way to get it back after some chages, but you could do that in some your ways, for example add custom attributes to label

    textLabel.Attributes.Add("data", textLabel.Text);
    

    and then use it on your page. Or cache label value using js code on page startup or statically.

  • Create a property that wraps the text assignment. Before the assignment take the current value and assign it to a hidden input or stick it in the session or viewstate.

    Create a property that retrieves the previous value from the hidden input or session or viewstate.

    Could get fancy and extend the label to add a PreviousValue property. Not sure how this would work in practice though.

Sort a mysql table using php,ajax and jquery

Hello Everyone Ok here is the deal i am building a messaging system by php,ajax,jquery and mysql i add the new message and i add in 2 rows now what i want to do is to send an ajax request to server and recieve an updated version of the table but sorted So how can i do so

//here i add and call the message the message

function addMsg()
 {
      //alert(post);
  $.get("db.php",$('form').serialize(),
     function(data){
   getMsg(data);},"html");
}

function getMsg(data) { alert(data); $("#t1").append(data); } //php

 $sql="INSERT INTO -----

mysql_query($sql) or die(mysql_error()); 


$result = mysql_query("SELECT ----");

    while($row = mysql_fetch_assoc($result))
   {     
   echo "<tbody><tr><td>".""."</td><td>".$row["col"]."</td><td>".$row["col"]."</td><td></td><td></td><tr><td></td><td colspan='4'>".$row["col"]."</td></tr></tbody>"; 
   }

?>

//Now for sorting //javascript

function sort()
 {
  $.ajax({
    url: "sort.php",
    dataType: "text",
    success: function(data){
    $("t1").text(data);
        }

  });

 }

//php

$result = mysql_query("SELECT * FROM table ORDER BY col desc");

   while($row = mysql_fetch_array($result))
        {  
     echo "<tbody><tr><td>"."&#8226;"."</td><td>".$row["col"]."</td><td>".$row["col"]."</td><td></td><td></td><tr><td></td><td colspan='4'>".$row["col"]."</td></tr></tbody>"; 
     }

?>

From stackoverflow
  • Use ORDER BY when you do the SELECT. Check this: http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html

  • Ok here is all i can do but still doesn't work any ideas Come on gurus i need help

    //index.php

    From

    //ajax.js

    function sort(orderByType)
     {
      $.ajax({
        url: "sort.php",
        type:"get",
        data: "orderby="+orderByType,
        success:function(data){
       alert(data);
        $("t1").text(data);}
      });
    
     }
    

    //sort.php

    $con = mysql_connect("localhost","root","root");
    if (!$con) {
     die('Could not connect: ' . mysql_error());
    }
    

    $orderBy = $_GET['orderby'];

    mysql_select_db("icrisis", $con);
    
    $result = mysql_query("SELECT * FROM messages,user  
             where user_id = from_user
             ORDER BY user_name".$orderBy);
    
    
     while($row = mysql_fetch_array($result))
       {  
      echo "<tbody><tr><td>"."&#8226;"."</td><td>".$row["Time_Date"]."</td><td>".$row["player_name"]."</td><td></td><td></td><tr><td></td><td colspan='4'>".$row["msg_desc"]."</td></tr></tbody>";
         }
    
    
    mysql_close($con);
    

    ?>

    It doesn't see the $orderBy And then i want to add the new order to my page how could that be done

Any known resources for Secured Socket Programming with Jetty?

Do you guys know fine tutorials, sample codes for SSL socket programming with Jetty? I am going to implement some secured applications with Jetty.. :)

From stackoverflow

SAXON.NET XSLT 2.0 Processor

I am using the open source Saxon XSLT processor for .NET to execute some 2.0 transforms.

I reference the saxon9api.dll as I would any other dll, and can compile code against this. However Visual Studio does not show any intellisense making the IDE as useful as notepad.

The saxon9api.dll is using the IKVM Java for .NET platform, and I wonder if this is the causing VS a problem. Reflector can inspect the DLL without issue, but I suspect VS is not happy for some reason.

Any ideas?

EDIT:

Surprised that no one else has encountered this behaviour seeing as Microsoft recommend the use of Saxon in the absense of built in functionality in the framework.

I think I will reword the question to be about assemblies running under IKVM not showing intellisense although I will need to find another IKVM based project to prove that this is the case first...

From stackoverflow
  • You might be better off asking this question on the xsl-list mailing list. I thinkthat you are asking the sort of question that requires a Michael Kay answer and he definitely reads the list. The list is at link text

Complete list of defines for Delphi versions

Does anyone know of a good place where I can find the complete list of version defines for all the Delphi versions, right up to Delphi 2009?

From stackoverflow
  • You could us the GX_CondDefine.inc From the great gexperts plugin:

    {$IFDEF CONDITIONALEXPRESSIONS}
      {$IFDEF BCB}
        {$DEFINE GX_BCB}
      {$ELSE}
        {$DEFINE GX_Delphi}
      {$ENDIF}
    
      {$IF CompilerVersion >= 14}
        {$DEFINE GX_VER140_up} // Delphi 6
        {$IFDEF LINUX}
          {$DEFINE GX_KYLIX}
          {$IF RTLVersion = 14.2}
            {$DEFINE GX_KYLIX2} // Kylix 2
          {$IFEND}
          {$IF RTLVersion = 14.5}
            {$DEFINE GX_KYLIX3} // Kylix 3
          {$IFEND}
        {$ENDIF}
        {$IF CompilerVersion >= 15}
          {$DEFINE GX_VER150_up}  // Delphi 7
          {$IF CompilerVersion >= 16}
            {$DEFINE GX_VER160_up}  // Delphi 8
            {$IF CompilerVersion >= 17}
              {$DEFINE GX_VER170_up}  // Delphi 9/2005
              {$IF CompilerVersion >= 18}
                {$DEFINE GX_VER180_up}  // BDS 2006
                {$IFDEF VER185}
                  {$DEFINE GX_VER185_up}  // Delphi 2007
                {$ENDIF}
                {$IF CompilerVersion >= 19}
                  {$DEFINE GX_VER190_up}  // Delphi .NET 2007
                  {$IF CompilerVersion >= 20}
                    {$DEFINE GX_VER200_up}  // RAD Studio 2009
                  {$IFEND}
                {$IFEND}
              {$IFEND}
            {$IFEND}
          {$IFEND}
        {$IFEND}
      {$IFEND}
    {$ELSE not CONDITIONALEXPRESSIONS}
      Sorry, but this version of GExperts does not support the IDE
      you are using. Please visit the GExperts web site at
      http://www.gexperts.org/ to obtain more information about
      support for your IDE.
    {$ENDIF}
    
  • A very, very good Delphi version include file is the jedi.inc from the the JEDI Code Library (JCL).

    It is always up-to-date and it includes a lot of "Feature Directives" like SUPPORTS_INT64 or SUPPORTS_UNICODE_STRING.

    Here is the SVN link.

    Davy Landman : Agreed, that one is very extensive!
    Gustavo Carreno : I think this is the one I would recommend in the future !!
    Marco van de Voort : This is the original document that I sent to Jedi about this, it provides a rationale why to do this: http://www.stack.nl/~marcov/porting.pdf (chapter 2)

How do you change your Rails App Data?

I have seen a lot of talk regarding ActiveRecord Migrations and whether or not they should be used to change data within your application, some people saying yes some saying no. My question is if you are not using Migrations to do this then what are you using? Just another script that you write?

I am after suggestitions on alternative ways and why they might be a better idea than just using migrations.

From stackoverflow
  • One problem comes if you use the provided

    rake db:reset
    

    and

    rake db:schema:load
    

    tasks, which use schema.rb as the basis for setting up your database. So no data gets loaded and you're stuck.

    In Agile Web Development with Rails, Third Edition, which you should get (if the Ruby book is the "Pickaxe" book, should this be the "Hammock" book, btw?) if you haven't done so already, DHH says:

    ...migrations aren’t really meant to carry seed data. They’re too temporal in nature to do that reliably. Migrations are here to bring you from one version of the schema to the next, not to create a fresh schema from scratch—we have the db/schema.rb file for that.

    So, as soon as you actually get going with a real application, people won’t be running your early migrations when they set up the application. They’ll start from whatever version is stored in db/schema.rb and ignore all those previous migrations. This means that any data created by the migrations never make it into the database, so you can’t rely on it.

    There are many alternative ways to have more permanent seed data. The easiest is probably just to create a new file in db/seed.rb, which contains those Product.create calls that’ll do the setup. This file can then be called after rake db:schema:load creates the initial schema.

  • a lot of times, migrations are the best fit and cannot be replaced with a separate script. Imagine the following scenario: the application is already in use with live data; the code column contains a code in the form "name-zip_code" (yeah I know it's ugly, but it happens), and you want to split that into two columns, 'name' and 'zip_code', while getting rid of the 'code' column.

    
    def self.up
      add_column :companies, :zip_code, :integer
      add_column :companies, :name, :string
      Company.reset_column_information
      Company.find(:all).each do |company|
        name, zip_code = company.code.split('-')
        company.update_attributes(:name => name, :zip_code => zip_code)  
      end
      remove_column :companies, :code
    end
    

    in this case, the code column cannot be removed before the data is transfered to the name and zip code columns.

  • When I need to modify some data in the databse, I will create a Rake task that runs some library function to do the work. This way, the data manipulation will be repeatable and if required, can be run from a migration as well.