Thursday, May 5, 2011

If statement SQL

Hi i want to run an if statement but keep getting syntax errors near all my AS aliases, what am i doing wrong?

SELECT

IF @Origin = 'ALL'


(SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) <= 60) AS OneHour,
(SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 61 AND 120) AS TwoHour,
(SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 121 AND 180) AS ThreeHour,
(SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 181 AND 240) AS FourHour,
(SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 241 AND 480) AS EightHour,
(SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND  DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 481 AND 1440) AS TwentyFourHour,
(SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 1441 AND 2880) AS FortyEightHour,
(SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) >=2881) AS PlusFortyEightHour

END
ELSE

(SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND (TBL_REPAIR_ORDER.ORIGIN = @ORIGIN) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) <= 60) AS OneHour,
(SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND (TBL_REPAIR_ORDER.ORIGIN = @ORIGIN) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 61 AND 120) AS TwoHour,
(SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND (TBL_REPAIR_ORDER.ORIGIN = @ORIGIN) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 121 AND 180) AS ThreeHour,
(SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND (TBL_REPAIR_ORDER.ORIGIN = @ORIGIN) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 181 AND 240) AS FourHour,
(SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND (TBL_REPAIR_ORDER.ORIGIN = @ORIGIN) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 241 AND 480) AS EightHour,
(SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND (TBL_REPAIR_ORDER.ORIGIN = @ORIGIN) AND  DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 481 AND 1440) AS TwentyFourHour,
(SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND (TBL_REPAIR_ORDER.ORIGIN = @ORIGIN) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 1441 AND 2880) AS FortyEightHour,
(SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND (TBL_REPAIR_ORDER.ORIGIN = @ORIGIN) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) >=2881) AS PlusFortyEightHour
END
From stackoverflow
  • IF condition
    BEGIN
    -- ...
    END
    ELSE
    BEGIN
    -- ...
    END
    
    John Saunders : If in doubt, simplify. Try SELECT IF condition BEGIN SELECT 1 AS OneHour, SELECT 2 AS TwoHour, etc. You'll find the solution quickly.
  • You forgot the BEGIN...

    IF (@Origin = 'ALL')
    BEGIN
    --
    END
    ELSE
    BEGIN
    --
    END
    
  • I've just tried the following as a test and it works fine. You should be able to use this as a starting point for your example.

    DECLARE @Origin NVARCHAR(200)
    SET @Origin = 'ALL'
    IF @Origin = 'ALL'
        BEGIN
        (SELECT ('Test') AS HI)
        END
    ELSE
        BEGIN
         (SELECT ('Test2') AS HI)
        END
    
  • There are two problems. The lack of a BEGIN, and also, the SELECT needs to be within each of the IF statements. You cannot have an inline IF within a SELECT, if you need to do this you can use a CASE statement.

    IF @Origin = 'ALL'
    BEGIN
     SELECT
      (SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) <= 60) AS OneHour,
      (SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 61 AND 120) AS TwoHour,
      (SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 121 AND 180) AS ThreeHour,
      (SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 181 AND 240) AS FourHour,
      (SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 241 AND 480) AS EightHour,
      (SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND  DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 481 AND 1440) AS TwentyFourHour,
      (SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 1441 AND 2880) AS FortyEightHour,
      (SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) >=2881) AS PlusFortyEightHour
    END
    ELSE
    BEGIN
     SELECT
      (SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND (TBL_REPAIR_ORDER.ORIGIN = @ORIGIN) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) <= 60) AS OneHour,
      (SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND (TBL_REPAIR_ORDER.ORIGIN = @ORIGIN) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 61 AND 120) AS TwoHour,
      (SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND (TBL_REPAIR_ORDER.ORIGIN = @ORIGIN) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 121 AND 180) AS ThreeHour,
      (SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND (TBL_REPAIR_ORDER.ORIGIN = @ORIGIN) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 181 AND 240) AS FourHour,
      (SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND (TBL_REPAIR_ORDER.ORIGIN = @ORIGIN) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 241 AND 480) AS EightHour,
      (SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND (TBL_REPAIR_ORDER.ORIGIN = @ORIGIN) AND  DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 481 AND 1440) AS TwentyFourHour,
      (SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND (TBL_REPAIR_ORDER.ORIGIN = @ORIGIN) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 1441 AND 2880) AS FortyEightHour,
      (SELECT COUNT(*)  FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF WHERE (TBL_PARTORDER.RAISED IS NOT NULL) AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103))) AND (TBL_PROPERTY.CONTRACT = @CONTRACT) AND (TBL_REPAIR_ORDER.ORIGIN = @ORIGIN) AND DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) >=2881) AS PlusFortyEightHour
    END
    
    Arvo : You did post while as I was writing same thing - instead voted you up :)
    John Saunders : @Robin, that's _cheating_! I wanted him to find that out by himself. You've just given it away. ;-)
    Robin Day : Sorry, have upvoted you to make up for it :)
    Robin Day : The main point here is that IF is generally not used for what you were trying. Instead you would use the CASE statement. On a completely different note though, I think you will find there is much much more you can do to this statement to make it better. There is a lot of repetition of which you can probably find an alternative.
    Robin Day : @elphj: I would suggest looing at a case statement to calculate the onehour, threehour items as a column and then performing a GROUP BY on that column to retrieve the data you are after. That way you will receive a record for each time frame with the count. If you then do need this for each column you can perform a PIVOT to get it exactly as you have it now. I suggest having a play with that and then maybe asking another question related to that if you struggle.
  • I think your query would be easier to read if you use this approach:

    SELECT
        SUM(
            CASE WHEN DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) <= 60 THEN 1
            ELSE 0
        ) AS OneHour,
        SUM(
            CASE WHEN DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN 61 AND 120 THEN 1
            ELSE 0
        ) AS TwoHour,
        ...
    FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID 
        INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF 
    WHERE (TBL_PARTORDER.RAISED IS NOT NULL) 
        AND (TBL_PROPERTY.CONTRACT = @CONTRACT)
        AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) 
        AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103)))
    

    Or better yet, pull the time window definitions into a table:

    create table TimeWindow (MinuteLowerBound int , MinuteUpperBound int , TimeWindowName varchar(32))
    insert TimeWindow (MinuteLowerBound , MinuteUpperBound , TimeWindowName)
    select 0 as MinuteLowerBound , 60 as MinuteUpperBound , 'OneHour' as TimeWindowName
    union all select 61, 120, 'TwoHour'
    union all select 121, 180, 'ThreeHour'
    

    And then just join against the time window definitions:

    SELECT
        tw.TimeWindowName,
        count(*) as TimeWindowCount
    FROM TBL_PARTORDER INNER JOIN TBL_REPAIR_ORDER ON TBL_PARTORDER.ORDERID = TBL_REPAIR_ORDER.ORDERID 
        INNER JOIN TBL_PROPERTY ON TBL_REPAIR_ORDER.PROPREF = TBL_PROPERTY.PROPREF
        INNER JOIN TimeWindow as tw on DATEDIFF(mi, TBL_PARTORDER.RAISED, TBL_PARTORDER.RECEIVED) BETWEEN tw.MinuteLowerBound and tw.MinuteUpperBound
    WHERE (TBL_PARTORDER.RAISED IS NOT NULL) 
        AND (TBL_PROPERTY.CONTRACT = @CONTRACT)
        AND (TBL_PARTORDER.RAISED BETWEEN CONVERT(DATETIME,@STARTDATE, 103) 
        AND DATEADD(hh,23,CONVERT(DATETIME,@ENDDATE, 103)))  
    GROUP BY tw.TimeWindowName
    

How can I use Java to programmaticaly convert an Internal Stylesheet of a web-page to an inline one?

Is there a ready-made tool or utility that does that already

From stackoverflow
  • You could just open the CSS file and just embed its content into a style tag.

    It should not be that hard:

    FileReader frCSS = new FileReader("your_css.css");
    FileReader frHTML = new FileReader("your_html.html");
    FileWriter output = new FileWriter("result.html");
    

    Then parse frHTML and copy its content to output until you find the head opening tag. When you do, open a style tag and copy all contents from frCSS. Then, close the style tag and copy the remaining portion of frHTML.

    It's not pretty, but it can be done.

    Oren Yosifon : That would convert an External Stylesheet to Internal. I am interested in converting internal to inline, if possible, without the heavylifting of doing all the parsing myself...

Deploying a WebService in glassfish with init parameters

I've created a WebService using the JAX-WS API. This service runs without any problem using an Endpoint class.

main(String args[])
{
(...)
MyService service=new MyService();
service.setParam1("limit=100");
service.setParam2("hello");
service.setParam3("max-value=10");
Endpoint endpoint = Endpoint.create(service);
endpoint.publish("http://localhost:8090/ws");
(...)
}

now, I'd like to deploy this service in glassfish. However, as I wrote in my example, I'd like to initialize my service with a some parameters. How can I achieve this ? should I use another API ?

Many thanks in advance

From stackoverflow

Serialise to XML and include the type of the serialised object

In a previous question about serialising an object to an XmlDocument in C#, I needed to serialise some fault information to an XmlDocument that was returned from a asmx-style webservice call. On the client I need to de-serialise the XmlDocument back to an object.

This is straightforward enough if you know the type, but I realised I wanted a flexible approach where the type to de-serialise to is also encoded in the XmlDocument. I'm currently doing it manually by adding an XmlNode to the XmlDocument that has the type name, calculated as follows:

    Type type = fault.GetType();
    string assemblyName = type.Assembly.FullName;

    // Strip off the version and culture info
    assemblyName = assemblyName.Substring(0, assemblyName.IndexOf(",")).Trim();

    string typeName = type.FullName + ", " + assemblyName;

Then on the client I first get this type name back from the XmlDocument, and create the type object that is passed into the XmlSerialiser thus:

        object fault;
        XmlNode faultNode = e.Detail.FirstChild;
        XmlNode faultTypeNode = faultNode.NextSibling;

        // The typename of the fault type is the inner xml of the first node
        string typeName = faultTypeNode.InnerXml;
        Type faultType = Type.GetType(typeName);

        // The serialised data for the fault is the second node
        using (var stream = new StringReader(faultNode.OuterXml))
        {
            var serialiser = new XmlSerializer(faultType);
            objectThatWasSerialised = serialiser.Deserialize(stream);
        }

        return (CastToType)fault;

So this is a brute-force approach, and I was wondering if there's a more elegant solution that somehow includes the typename of the serialised type automatically, rather than manually recording it elsewhere?

From stackoverflow
  • Neil, why do you need it to be the same type on both the client and the server?

    Are you still using ASMX on the client? That would be a reason, as ASMX does not properly support faults.

    Also, do you have so many different fault types that a simple switch statement can't determine the correct type to use?

    Neil Barnwell : I'm using asmx on the server and client, yes. I'm sort've implementing a kind of half-baked WCF-like fault system because on the client I'm using an interface to the asmx service and I don't want users of that interface to get SoapExceptions, so they get something I've called a ServiceException instead, with a Fault property. That fault property is returned to the asmx client in the SoapException.Detail property, hence the XmlDocument/XmlNode serialisation. I don't have many fault types at the moment, but I want flexibility to add more to the server without breaking deployed clients.
    John Saunders : So, you're not reinventing the wheel; you're reinventing WCF.
  • I had faced a similar problem and I came up with the same solution. As far as I am concerned, that is the only way to keep types together with values in XML serialization.

    I see you are cutting assembly version out as I did too. But I'd like to mention, that you will have troubles with generic types as theirs signature looks like that:

    System.Nullable`1[[System.Int, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
    

    So I made a function to only cut out the assembly version(s), which seems to be enough to get rid of versioning problems:

        private static string CutOutVersionNumbers(string fullTypeName)
        {
            string shortTypeName = fullTypeName;
            var versionIndex = shortTypeName.IndexOf("Version");
            while (versionIndex != -1)
            {
                int commaIndex = shortTypeName.IndexOf(",", versionIndex);
                shortTypeName = shortTypeName.Remove(versionIndex, commaIndex - versionIndex + 1);
                versionIndex = shortTypeName.IndexOf("Version");
            }
            return shortTypeName;
        }
    

What is the difference between UML 2.1.2 and UML 2.2

I am evaluating a tool which says that it supports UML 2.2. However if I search on internet, I can't find what incremental change has occured between two version.

And yes, I tried to go through OMG documents, but those are too dense to read. Is there a simple explanation anywhere?

From stackoverflow
  • Not sure what your reference level of UML is, but the UML 2.2 specifications with change bars shows you all the changes. It just takes time page turning. It's perhaps easier to read through the RTF Report for revision 2.2.

  • I don't think there's a clear overview of the changes in 2.2. There's a UML 2.2 specification document with change bars: it marks the changed sections as opposed to version 2.1.2. It's really the best way to view those changes - again, there's no real overview, at least none that I could find. You can view the document (PDF) here.

    I've skimmed the document a bit. They're mostly minor changes. Some of the changes I came across you can quickly find in:

    • 8.3 (Class Descriptions)
    • 8.3.2 (ComponentRealization)
    • 10.2 (Deployments - Abstract Syntax)
    • 11.2 (Abstract Syntax)
    • 11.3.12 (ClearStructuralFeatureAction)
    • 11.3.19 (InputPin)
    • 11.3.33 (ReadLinkAction)
    • 11.3.47 (StartObjectBehaviorAction)
    • 11.3.55 (WriteStructuralFeatureAction)
    • 15.2 (State Machines - Abstract syntax)
    Varun Mahajan : Thank you, you saved me a lot of time.
    Razzie : You're welcome. Note though, that the list is not complete. However, with the change bars, it is not too hard to quickly view what sections have changed. Good luck!

Good books or online resources for learning Hibernate

What I found so far are some online resources like this:

http://www.torsten-horn.de/techdocs/java-hibernate.htm (GER)

https://www.hibernate.org/5.html (Hibernate Docs)

http://docs.jboss.org/hibernate/stable/core/reference/en/html/tutorial.html

http://www.manning.com/bauer2/chapter2.pdf (Sample chapter of Java Persistence with Hibernate)

http://www.wenzlaff.de/hibernate.html (GER)

So thats a good way to start but i wonder if you can recommand any good books for learning Hibernate, or maybe you know some other very good online resource for learning it?

From stackoverflow
  • Visit www.flazx.com. I guess Professional Hibernate (Programmer to Programmer) would be a nice selection

  • try search on scribd.com

  • These are some links I have bookmarked:

    However, in my opinion Java Persistence with Hibernate definitely worths the money and time to read it.

  • Hibernate in Action by Christian Bauer and Gavin King

    Its slightly out of date, but is an excellent introduction.

  • Java Persistence with Hibernate is the second edition of "Hibernate in Action". They changed the name since they now provide JPA examples as well as Hibernate.

    toolkit : excellent book - covers both native Hibernate, and JPA using Hibernate.

identity to be incremented only if record is inserted

sql server 2005 : i have a column empid in employee table with identity on.if there is some error while inserting data into table .identity is incremented .i want identity to be incremented only if record is inserted .like if i have generated emp id from 1 to 5 and then on 6th record insertion error ocurrs.and on next record insertion identity value will be 7 .i want it to be 6.

From stackoverflow
  • I don't think this can be done. If you want your identity numbers to be exactly sequential then you may have to generate them yourself, rather than using the SQL Identity feature.

    edit: Even rolling back the failed transactions will not make the Identity count go back down, this is by design, see this other question.

  • Why do you want to do that ?

    The identity column should only be used as an 'internal administrative value' for the database, and it should have no 'business value', so why does it matter that there are gaps in that sequence ?
    If identity is used correctly, then users of your software will never be faced with the column that has an identity value; you just use it to uniquely identify a record.

  • When you need to have this specific behaviour you should use stored procedures to generate the ID. This way you can really to a rollback. But keep in mind that the current behaviour is by purpose. Transaction isolation and different read levels (dirty reads) will most likely get you into trouble when you don't use locking on that id field in your masterdata table that holds the current or next ID value.

  • What valid business reason do you have for caring if there are gaps? There is no reason for the database to care and every reason to want to make sure that identity values are never reused for something else as they can cause major problems with data integrity with looking up information based on old reports, etc. Suppose you have a report that shows the orders last month and then you delete one of the records becasue the customer was duplicated and thus dedupped. Then you reuse the identity field for the dupped customer that was removed. NOw someone looknig at last month's report goes to look up customer 12345 and the data associated with that cuisotmer belongs to John Smith rather than Sally Jones. BUt the person doesn;t know that because she is using an aggreagate, so now she has incorrect information that was totally avoidable. If she was looking up the delted customer, the process instead could have redirected her to the correct customer left after the dedupping.

Difference between GIT and CVS

What is the difference between git and cvs version control systems?

I have been happily using CVS for over 10 years and have been told that GIT is much better. Could someone please explain what the difference between the two is and why one is better than the other?

From stackoverflow
  • The Git website explains this best probably.

    My pet feature is being able to do commits when offline. And the speed, the sheer blazing speed at which everything except pushing and pulling happens. (And these operations are by design nondestructive, so you can push/pull when you go grab a coffee if your central repo is lagged.) Another nice thing is that it comes batteries included: the builtin gitk is a good enough history viewer; git gui is a good enough commit tool; with output colorization, git add -i, git add -p, git rebase -i are good enough interactive interfaces; git daemon and git instaweb are good enough for ad-hoc collaboration if you don't want to / can't fiddle with your central repo.

  • You can find a lot of information here: http://whygitisbetterthanx.com/

    Although cvs is not included in there, svn is (which is cvs done right). So everything that applies to svn does also apply to cvs.

    hasen j : and add to it the difference between svn and cvs
  • Git is a DVCS, as opposed to CVS being a centralized one. Simplistic description will be: you get all benefits of version control when you're not connected to any of multiple possible repositories, plus operations are faster.

  • There's a nice chart that compares several version control systems here.

    Jakub Narębski : Note that data for this tool was taken from "Better SCM Initiative" comparison of version control systems, and that it contains a few quite severe wrong information about Git.
  • This talk by Linus (the original author of git) pretty much sums it up.

    Google Tech Talks: Linus Torvalds on Git

    Attention: Highly opinionated talk.

  • The main difference is that (as it was already said in other responses) CVS is (old) centralized version control system, while Git is distributed.

    But even if you use version control for single developer, on single machine (single account), there are a few differences between Git and CVS:

    • Setting up repository. Git stores repository in .git directory in top directory of your project; CVS require setting up CVSROOT, a central place for storing version control info for different projects (modules). The consequence of that design for user is that importing existing sources into version control is as simple as "git init && git add . && git commit" in Git, while it is more complicated in CVS.

    • Atomic operations. Because CVS at beginning was a set of scripts around per-file RCS version control system, commits (and other operations) are not atomic in CVS; if an operation on the repository is interrupted in the middle, the repository can be left in an inconsistent state. In Git all operations are atomic: either they succeed as whole, or they fail without any changes.

    • Changesets. Changes in CVS are per file, while changes (commits) in Git they always refer to the whole project. This is very important paradigm shift. One of consequences of this is that it is very easy in Git to revert (create a change that undoes) or undo whole change; other consequence is that in CVS is easy to do partial checkouts, while it is currently next to impossible in Git. The fact that changes are per-file, grouped together led to invention of GNU Changelog format for commit messages in CVS; Git users use (and some Git tools expect) different convention, with single line describing (summarizing) change, followed by empty line, followed by more detailed description of changes.

    • Naming revisions / version numbers. There is another issue connected with the fact that in CVS changes are per files: version numbers (as you can see sometimes in keyword expansion, see below) like 1.4 reflects how many time given file has been changed. In Git each version of a project as a whole (each commit) has its unique name given by SHA-1 id; usually first 7-8 characters are enough to identify a commit (you can't use simple numbering scheme for versions in distributed version control system -- that requires central numbering authority). In CVS to have version number or symbolic name referring to state of project as a whole you use tags; the same is true in Git if you want to use name like 'v1.5.6-rc2' for some version of a project... but tags in Git are much easier to use.

    • Easy branching. Branches in CVS are in my opinion overly complicated, and hard to deal with. You have to tag branches to have a name for a whole repository branch (and even that can fail in some cases, if I remember correctly, because of per-file handling). Add to that the fact that CVS doesn't have merge tracking, so you have to either remember, or manually tag merges and branching points, and manually supply correct info for "cvs update -j" to merge branches, and it makes for branching to be unnecessary hard to use. In Git creating and merging branches is very easy; Git remembers all required info by itself (so merging a branch is as easy as "git merge branchname")... it had to, because distributed development naturally leads to multiple branches.

      This means that you are able to use topic branches, i.e. develop a separate feature in multiple steps in separate feature branch.

    • Rename (and copy) tracking. File renames are not supported in CVS, and manual renaming might break history in two, or lead to invalid history where you cannot correctly recover the state of a project before rename. Git uses heuristic rename detection, based on similarity of contents and filename (This solution works well in practice). You can also request detecting of copying of files. This means that:

      • when examining specified commit you would get information that some file was renamed,
      • merging correctly takes renames into account (for example if the file was renamed only in one branch)
      • "git blame", the (better) equivalent of "cvs annotate", a tool to show line-wise history of a file contents, can follow code movement also across renames
    • Binary files. CVS has only a very limited support for binary files (e.g. images), requiring users to mark binary files explicitly when adding (or later using "cvs admin", or via wrappers to do that automatically based on file name), to avoid mangling of binary file via end-of-line conversion and keyword expansion. Git automatically detects binary file based on contents in the same way CNU diff and other tools do it; you can override this detection using gitattributes mechanism. Moreover binary files are safe against unrecoverable mangling thanks to default on 'safecrlf' (and the fact that you have to request end-of-line conversion, although this might be turned on by default depending on distribution), and that (limited) keyword expansion is a strict 'opt-in' in Git.

    • Keyword expansion. Git offers a very, very limited set of keywords as compared to CVS (by default). This is because of two facts: changes in Git are per repository and not per file, and Git avoids modifying files that did not change when switching to other branch or rewinding to other point in history. If you want to embed revision number using Git, you should do this using your build system, e.g. following example of GIT-VERSION-GEN script in Linux kernel sources and in Git sources.

    • Amending commits. Because in distributed VCS such as Git act of publishing is separate from creating a commit, one can change (edit, rewrite) unpublished part of history without inconveniencing other users. In particular if you notice typo (or other error) in commit message, or a bug in commit, you can simply use "git commit --amend". This is not possible (at least not without heavy hackery) in CVS.

    • More tools. Git offers much more tools than CVS. One of more important is "git bisect" that can be used to find a commit (revision) that introduced a bug; if your commits are small and self-contained it should be fairly easy then to discover where the bug is.


    If you are collaboration with at least one other developer, you would find also the following differences between Git and CVS:

    • Commit before merge Git uses commit-before-merge rather than, like CVS, merge-before-commit (or update-then-commit). If while you were editing files, preparing for creating new commit (new revision) somebody other created new commit on the same branch and it is now in repository, CVS forces you to first update your working directory and resolve conflicts before allowing you to commit. This is not the case with Git. You first commit, saving your state in version control, then you merge other developer changes. You can also ask the other developer to do the merge and resolve conflicts.

      If you prefer to have linear history and avoid merges, you can always use commit-merge-recommit workflow via "git rebase" (and "git pull --rebase"), which is similar to CVS in that you replay your changes on top of updated state. But you always commit first.

    • No need for central repository With Git there is no need to have single central place where you commit your changes. Each developer can have its own repository (or better repositories: private one in which he/she does development, and public bare one where she/he publishes that part which is ready), and they can pull/fetch from each other repositories, in symmetric fashion. On the other hand it is common for larger project to have socially defined/nominated central repository from which everyone pull from (get changes from).


    Finally Git offers many more possibilities when collaboration with large number of developers is needed. Below there are differences between CVS in Git for different stages of interest and position in a project (under version control using CVS or Git):

    • lurker. If you are interested only in getting latest changes from a project, (no propagation of your changes), or doing private development (without contributing back to original projects); or you use foreign projects as a basis of your own project (changes are local and doesn't it make sense to publish them).

      Git supports here anonymous unauthenticated read-only access via custom efficient git://protocol, or if you are behind firewall blocking DEFAULT_GIT_PORT (9418) you can use plain HTTP.

      For CVS most common solution (as I understand it) for read-only access is guest account for 'pserver' protocol on CVS_AUTH_PORT (2401), usually called "anonymous" and with empty password. Credentials are stored by default in $HOME/.cvspass file, so you have to provide it only once; still, this is a bit of barrier (you have to know name of guest account, or pay attention to CVS server messages) and annoyance.

    • fringe developer (leaf contributor). One way of propagating your changes in OSS is sending patches via email. This is most common solution if you are (more or less) accidental developer, sending single change, or single bugfix. BTW. sending patches might be via review board (patch review system) or similar means, not only via email.

      Git offers here tools which help in this propagation (publishing) mechanism both for sender (client), and for maintainer (server). For people who want send their changes via email there is "git rebase" (or "git pull --rebase") tool to replay your own changes on top of current upstream version, so your changes are on top of current version (are fresh), and "git format-patch" to create email with commit message (and authorship), change in the form of (extended) unified diff format (plus diffstat for easier review). Maintainer can turn such email directly into commit preserving all information (including commit message) using "git am".

      CVS offer no such tools: you can use "cvs diff" / "cvs rdiff" to generate changes, and use GNU patch to apply changes, but as far as I know there is no way to automate applying commit message. CVS was meant to be used in client <-> server fashion...

    • lieutenant. If you are maintainer of separate part of a project (subsystem), or if development of your project follows "network of trust" workflow used in development of Linux kernel... or just if you have your own public repository, and the changes you want to publish are too large to send via email as patch series, you can send pull request to (main) maintainer of project.

      This is solution specific to distributed version control systems, so of course CVS doesn't support such way of collaboration. There is even a tool called "git request-pull" which help to prepare email to send to maintainer with request to pull from your repository. Thanks to "git bundle" you can use this mechanism even without having public repository, by sending bundle of changes via email or sneakernet. Some of Git hosting sites like GitHub have support for notifying that somebody is working (published some work) on your project (provided that he/she uses the same Git hosting site), and for PM-ing a kind of pull request.

    • main developer, i.e. somebody who directly publish his/her changes (to main/canonical repository). This category is broader for distributed version control systems, as having multiple developers with write access to central repository is not only possible workflow (you can have single maintainer who pushes changes to canonical repository, a set of lieutenants/subsystem maintainers from which he/she pulls, and broad range of leaf developers who send patches via mail either to maintainer/project mailing list, or to one of lieutenants/submaintainers).

      With Git you have choice of using SSH protocol (git protocol wrapped in SSH) to publish changes, with tools such as "git shell" (to help security, limiting access of shell accounts) or Gitosis (to manage access without requiring separate shell accounts), and HTTPS with WebDAV, with ordinary HTTP authentication.

      With CVS there is a choice between custom unencrypted (plain text) pserver protocol, or using remote shell (where you really should use SSH) to publish your changes, which for centralized version control system means committing your changes (creating commits). Well, you can also tunnel 'pserver' protocol using SSH, and there are thir party tools automating this... but I don't think this is as easy as e.g. Gitosis.

    In general distributed version control systems, such as Git, provide much wider selection of possible workflows. With centralized version control systems, such as CVS, by necessity you have to distinguish between people with commit access to repository, and those without... and CVS doesn't offer any tools to help with accepting contributions (via patches) from people without commit access.

    Karl Fogel in Producing Open Source Software in section about version control states that it is better to not provide too strict, rigid and rigorous controls on areas where one is allowed to make changes to public repository; it is much better to rely (for this) on social restrictions (such as code review) than on technical restrictions; distributed version control systems reduce that IMHO even further...

    HTH (Hope That Helps)

    Richard Morgan : Excellent answer!
    Chris Huang-Leaver : Wow! That's more of a book you have written there!
    Krzysztof Koźmic : Jakub, you should really get a blog :)
    samuil : Jakub is listed as one of five mine authors of GIT, thus exhaustive answer. If laws governing world were easy there would be only four people able to answer better ;)
    Jakub Narębski : @samuil: I'm not one of authors of Git. The number of commits are not everything. I'm active mainly in the area of gitweb (git web interface) only.
  • "happily using CVS for over x years", is an interesting idea :-) It's a huge step up from keeping lots of copies, but ...

    I'm guessing you have got used to all it's quirks, or don't do much branching and merging. There is a worse possibility;

    People in your organisation have got used to cvs limitations and your work practises have adapted accordingly;

    for example never having more than one developer work on one package at a time, only using branching in emergencies etc.

    The basic principle is the more difficult something is, the less people do it.

  • Eric Sink has been blogging about GIT and source control lately at http://www.ericsink.com/archive_index.html.

  • I'm also a 10+ year mostly happy user of cvs, though I also like git, and with time will come to prefer it, though most of the projects I work on currently use cvs, or svn, and we can't seem to get the bureacracy where I work convinced to let us punch a git-hole through the firewall.

    A couple of things that make cvs nicer than it might otherwise be are cvsps, and another is either Andrew Morton's patch scripts, or quilt. Cvsps lets you reconstitute the multiple files of a commit into a single patch (and thus extract "changesets" from CVS) while quilt, or Andrew Morton's patch scripts allow you to commit sensible "changesets" into cvs pretty easily and comfortably, allowing you to work on mutliple things simultaneously while still keeping them separated prior to committing. CVS has its quirks, but I'm used to most of them.

Using the Selection service on something that is *not* a JFace view

I am building an image Editor as an Eclipse plugin.

I would like to use the Properties view to view & edit properties of the model underneath the image. Accordingly I am calling ..

getSite().setSelectionProvider( this );

.. within createPartControl, and implementing the ISelectionProvider interface in my EditorPart implementation, so that the model is returned as the selection (which must therefore implement the ISelection interface).

The next step is for the Editor to implement IAdaptable to supply an adapter for the selected object.

My problem however is that getAdapter is never called with IPropertySource.class, and therefore the Properties View never gets what it needs to make sense of the image model.

Your help is much appreciated.

M.

From stackoverflow
  • The answer in the end broke down into a few pieces ...

    1.) When your selection does change (if a user has zoomed into the image, for example) be sure to tell Eclipse this. It won't happen otherwise.

    2.) When sending your SelectionChangedEvent, wrap up your IAdaptable in a StructuredSelection object - otherwise the Properties view will ignore it.

    This boiled down to the following method

    public void fireSelectionChanged()
    {
        final SelectionChangedEvent event = new SelectionChangedEvent( this, new StructuredSelection( this  ) );
        Object[] listeners = selectionChangedListeners.getListeners();
        for (int i = 0; i < listeners.length; ++i) 
        {
            final ISelectionChangedListener l = (ISelectionChangedListener) listeners[i];
            SafeRunnable.run(new SafeRunnable() {
                public void run() {
                    l.selectionChanged( event );
                }
            });
        }
    }
    

    ... on an class that implemented ISelectionProvider & IAdaptable.

    M.

Why is floor() so slow?!

Hi all,

I wrote some code recently (ISO/ANSI C), and was surprised at the poor performance it achieved. Long story short, it turned out that the culprit was the floor() function. Not only it was slow, but it did not vectorize (with Intel compiler, aka ICL).

Here are some benchmarks for performing floor for all cells in a 2D matrix:

VC:  0.10
ICL: 0.20

Compare that to a simple cast:

VC:  0.04
ICL: 0.04

How can floor() be that much slower than a simple cast?! It does essentially the same thing (apart for negative numbers). 2nd question: Does someone know of a super-fast floor() implementation?

Thanks in advance,

Roger

PS: Here is the loop that I was benchmarking:

void Floor(float *matA, int *intA, const int height, const int width, const int width_aligned)
{
    float *rowA=NULL;
    int   *intRowA=NULL;
    int   row, col;

    for(row=0 ; row<height ; ++row){
        rowA = matA + row*width_aligned;
        intRowA = intA + row*width_aligned;
#pragma ivdep
        for(col=0 ; col<width; ++col){
            /*intRowA[col] = floor(rowA[col]);*/
            intRowA[col] = (int)(rowA[col]);
        }
    }
}
From stackoverflow
    1. They do not do the same thing. floor() is a function. Therefore, using it incurs a function call, allocating a stack frame, copying of parameters and retrieving the result. Casting is not a function call, so it uses faster mechanisms (I believe that it may use registers to process the values).
    2. Probably floor() is already optimized.
    3. Can you squeeze more performance out of your algorithm? Maybe switching rows and columns may help? Can you cache common values? Are all your compiler's optimizations on? Can you switch an operating system? a compiler? Jon Bentley's Programming Pearls has a great review of possible optimizations.
  • A couple of things make floor slower than a cast and prevent vectorization.

    The most important one:

    floor can modify the global state. If you pass a value that is to huge to be represented as an integer in float format, the errno variable gets set to EDOM. Special handling for NaNs is done as well. All this behaviour is for applications that want to detect the overflow case and handle the situation somehow (don't ask me how).

    Detecting these problematic conditions is not simple and makes up more than 90% of the excution time of floor. The actual rounding is cheap and could be inlined/vectorized. Also It's a lot of code, so inlining the whole floor-function would make your program run slower.

    Some compilers have special compiler flags that allow the compiler to optimize away some of the rarely used c-standard rules. For example GCC can be told that you're not interested in errno at all. To do so pass -fno-math-errno or -ffast-math. ICC and VC may have similar compiler flags.

    Btw - You can roll your own floor-function using simple casts. You just have to handle the negative and positive cases differently. That may be a lot faster if you don't need the special handling of overflows and NaNs.

  • Yes, floor() is extremely slow on all platforms since it has to implement a lot of behaviour from the IEEE fp spec. You can't really use it in inner loops.

    I sometimes use a macro to approximate floor():

    #define PSEUDO_FLOOR( V ) ((V) >= 0 ? (int)(V) : (int)((V) - 1))
    

    It does not behave exactly as floor(): for example, floor(-1) == -1 but PSEUDO_FLOOR(-1) == -2, but it's close enough for most uses.

    Charlie Somerville : Naive implementation. PSEUDO_FLOOR( x++ ) would break this.

How to use \L DOS command for creating Log file in SSIS

Hi,

I'm trying to use the below command to execute for generating the log file for SSIS package.

DTExec /FILE "C:\Documents and Settings\CP0808\My Documents\Test.dtsx" /logger "DTS.LogProviderTextFile;c:\log.txt"

But it got the error as below. Please advise.

Started: 12:03:20 AM Error: 2009-05-04 12:03:21.15 Code: 0xC001000E Source: Test Description: The connection "c:\log.txt" is not found. This error is thrown b y Connections collection when the specific connection element is not found. End Error Error: 2009-05-04 12:03:21.18 Code: 0xC001000E Source: Test Description: The connection "c:\log.txt" is not found. This error is thrown b y Connections collection when the specific connection element is not found. End Error Error: 2009-05-04 12:03:21.21 Code: 0xC02020EA Source: Test Log provider "{1AEAB490-1124-4A84-981F-7C1FDD80A721}" Description: The connection manager "c:\log.txt" is not found. A component fa iled to find the connection manager in the Connections collection. End Error

Please help me to solve this problem...

From stackoverflow
  • You need to set up the logging inside of BIDS. It will show you that you need to set up a connection manager, and that where you wrote "C:\log.txt", you're meant to have the name of the connection manager.

    sona : Thanks a lot John... I was fighting wth this error for 4 days... Noe it is working fine...

How to iterate over tabs in flex tabbar

Hi, I am a flex newbie. I need to disable some of the tabs in a flex tabbar specified, by configuration. I am having trouble in iterating over the tabs in the tab bar. If i use getChildAt() command, it does not disable the tab button, but the content of that tab button, so its no good.

Thanks and regards, Mohit Ranka

From stackoverflow
  • why not use a bindable to your configuration?

    something like

       enabled="{yourConfiguration.lastResult.enabled}"
    
    Mohit Ranka : because the requirement is more complex than this. bottleneck is i do not know how to iterate over tabs in tab bar.
  • When asking about code, always post a minimal test case. getChildAt() will work, so there's something else going on with your code.

    <mx:Script>
        <![CDATA[
            import mx.events.ItemClickEvent;
            import mx.controls.tabBarClasses.Tab;
            private function clickTab(event:ItemClickEvent):void {
                var target:TabBar = event.currentTarget as TabBar;
                var currTab:Tab;
                var parity:int = event.index & 1;
                /* disable all tabs at indices w/ same parity as clicked tab;
                   enable tabs of opposite parity.
                 */
                for (var i=0; i<target.numChildren; ++i) {
                   currTab = target.getChildAt(i) as Tab;
                   currTab.enabled = (i&1)^parity;
                }
            }
        ]]>
    </mx:Script>
    
    <mx:TabBar id="someTabs" itemClick="clickTab(event)">
        <mx:dataProvider>
         <mx:String>Foo</mx:String>
         <mx:String>Bar</mx:String>
         <mx:String>Baz</mx:String>
         <mx:String>Bam</mx:String>
        </mx:dataProvider>
    </mx:TabBar>
    

How to get out of subversion source control in visual studio?

I have a solution that is source controlled with Subversion and AnkhSVN in Visual Studio 2008, but I would like to remove source control from it, how do I do that?

From stackoverflow
  • SVN, as opposed to the dreaded VSS, does not clutter your project files with its "bindings": it keeps all its system information in .svn or _svn subfolders inside every version-controlled directory. Thus, "removing" version control from a project effectively means deleting all these folders.

    This is tedious, however, so SVN has a special command called svn export which either "exports a clean directory tree from the repository specified by URL" or "exports a clean directory tree from the working copy ".

    Mark Dickinson : Yeah thats what I'd do, cheers :)
    Mark Dickinson : If you were using Tortoise, you could right click on the root folder of your solution and under the Tortoise SVN sub menu, click Export to gain access to the export command.
    Peter : svn export did the trick tx
    Wim Coenen : You can also export in place, i.e. strip a working copy from its .svn folders, with svn export --force .
  • Remove .svn folders and your source tree will not be versioned anymore.

  • As far as I know, ankhsvn may store bindings in the solution files. I think that you can remove these bindings (if you have them) by going to File -> Source control -> Change Source Control. In that dialog there should be a command to "Unbind" the projects.

    Note: I don't have that kind of source control where I am sitting right now so the menu names/locations might be a bit off (taken from human memory that, as we all know, may be a bit error prone), but it should at least be something similar.

    Bert Huijben : This step is optional in AnkhSVN (as registering in the solution and/or projects is optional for most project types), but you should do this if you did mark your project as managed by Subversion before.
  • If you want to remove the Subversion control of a file/folder, but want to leave it where it currently is, you can use the 'Delete (keep local)' option on TortoiseSVN. To see this option you must hold down shift when you right-click the file/folder, then it will appear in the context menu.

    Bert Huijben : This will not remove the administrative area in the project; it will just mark them to be deleted from sourcecontrol on the next commit. (And you can never delete the root of your working copy).

Url Rewriting problem

Hi,

Presently I am working with asp.net with c#. In my project has requirement of url rewriting functionality. I did with my local iis but when it comes to production it's not working. Is there any way of doing url rewriting with change the iis setting in production environment.

ex:http://abc.com/profiles/suresh

I want this type of functionality in my production environment.

Please any one reply to this post its very very urgent.

Thanks in advance

From stackoverflow

ASP.Net MVC Simple Edit data from default template

when creating a new View and selecting Edit template, the template will create a textbox for the primary key which is not editable.

   <%=Html.TextBox("CompanyID", Model.CompanyID)%>

So, deleting the control from view, will cause the problem: the collection which is post to controller has the CompanyID=0 , so no edit will be done. But if I put back that line of code to view, the CompanyID in posted collection has the proper value. I am doing much like this tutorial: http://www.asp.net/learn/mvc/tutorial-21-vb.aspx , and there ( gray box above "Listing 6 – Controllers\HomeController.vb (Edit methods)" section ) it is saying you can delete the control, but its not working.. any advice?

Updated Ok, for more explain, here goes 2 problems:
problem 1 in this code:

<AcceptVerbs(HttpVerbs.Post)> _
Function Edit(ByVal movieToEdit As Movie) As ActionResult

if you remove the MovieID textbox from view the movieid in movietoedit collection is always zero, so the tutortial from the asp.net website wont work! if I want to delete the movieID from view, I have to pass the ID to my controller like this:

 <AcceptVerbs(HttpVerbs.Post)> _
Function Edit(ByVal ID as integer,ByVal movieToEdit As Movie) As ActionResult

now I can query Model using this ID.. thats no problem, but it takes me some times to figuring out, as I was doing step by step from the website !

Problem 2 So, How to do Edit without using the movieID in view, even in hidden textbox?
I am using this as my controller: ( using Enity framework )

  <AcceptVerbs(HttpVerbs.Post)> _
Function Edit(ByVal id As Integer, ByVal collection As Company) As ActionResult
    If Not ModelState.IsValid Then
        Return View()
    End If

    Try
        Dim c = _db.CompanySet.FirstOrDefault(Function(m) m.CompanyID = id)

        If c Is Nothing Then
            Return RedirectToAction("index")
        End If



        _db.ApplyPropertyChanges(c.EntityKey.EntitySetName, collection)
        _db.SaveChanges()

        Return RedirectToAction("Index")
    Catch ex As Exception
        Throw ex
    End Try
End Function

And if I remove CompanyID from my view ( textbox or hidden field ) it will give me this error from c.EntityKey.EntitySetName:
The ObjectStateManager does not contain an ObjectStateEntry with a reference to an object of type 'Companies.Company'.
and if I add something like

  <%= Html.TextBox("CompanyName", Model.CompanyName) %>

it will work fine .. I am confused!

note: I checked the code more than 10 times, and I wonder if there is anything I am doing wrong or the tutorial is wrong ..

From stackoverflow
  • If you are passing the id and updating specific fields through UpdateModel, it should work. You should better post your Edit method to let us see what's going on. Following example may illustrate the process I tried to explain.

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(int id, FormCollection formValues) {
    
        Page page = repo.GetPage(id); // returns page with specific id
        UpdateModel(page); // updates page with new form values
        repo.Save(); // saving all the changes
        return RedirectToAction("Details", new { id = page.id });
    
    }
    
    mohamadreza : please see the question, it is updated
  • The tutorial is right, you shouldn't leave a textbox with the id, I think they are assuming the id is part of your route, like /movies/edit/1. If that's not the case you can add it to the form action using the route collection or add a hidden field in the form.

    Adding the id to the route of the edit action:

        <% using (Html.BeginForm("Edit", "Controller", 
                  new {id = Model.Id}, FormMethod.Post))
       { %>
    

    Or a hidden field:

     <%=Html.Hidden("CompanyID", Model.CompanyID)%>
    
    mohamadreza : in my case there is no need for html.beginform values, because it is like :
    already, and i dont want to use hidden fields, is there any way?
  • Try this way:

    <AcceptVerbs(HttpVerbs.Post)> _
    Function Edit(<Bind(Exclude:="Id")> ByVal movieToEdit As Movie) As ActionResult
    

    For more information on ASP.Net MVC, see http://asp.net/learn/mvc