13 December 2012

Change back to Yahoo Classic Mail

Log into your mail account, disable java script in your browser, hit refresh, and then re-enable java script. its working for me so far.


Al 2012-12-13 funziona!

Trovato qui.

05 December 2012

Condizioni di ricerca dinamiche in T-SQL

ALTER PROCEDURE [dbo].[RichiesteManutenzione_SelectAll_sp]
   @Stato AS nvarchar(10) = NULL
 , @DataDa AS datetime = NULL
 , @DataA AS datetime = NULL
 , @Manutentore AS nvarchar(50) = NULL
AS

BEGIN
 SET NOCOUNT ON

 DECLARE @paramlist AS nvarchar(4000)
 DECLARE @sqW AS nvarchar(4000)
 DECLARE @sq AS nvarchar(4000)


 -- IMPOSTA I PARAMETRI PER LA sp_executeSql
 SET @paramlist = N'
    @Stato AS nvarchar(10) = NULL
  , @DataDa AS datetime = NULL
  , @DataA AS datetime = NULL
  , @Manutentore AS nvarchar(50) = NULL
  '
  

 -- IMPOSTA FILTRI
 SET @sqW = ''

 IF @Stato IS NOT NULL
  SET @sqW = @sqW + N'AND Stato = @Stato '
  
 IF @DataDa IS NOT NULL AND @DataA IS NOT NULL
  SET @sqW = @sqW + N'AND DataIns BETWEEN @DataDa AND @DataA + 1 '
 
 IF @Manutentore IS NOT NULL
  SET @sqW = @sqW + N'AND Manutentore = @Manutentore '


 -- IMPOSTA QUERY
 SET @sq = N'
 SELECT a.Id, a.Stato, a.Richiesta, a.Note, a.Richiedente, 
   a.DataIns, a.DataProgramma, a.DataChiusura, a.IdMacchina, a.MacchinaDenominazione, 
   a.IdElemento, a.ElementoDenominazione, a.Manutentore, 
   LTRIM(ISNULL(a.RespInternoCognome, '''') + '' '' + ISNULL(a.RespInternoNome, '''')) AS RespInterno
 FROM RichiesteManutenzione_tb a '
 
 IF LTRIM(@sqW) <> ''
  SET @sq = @sq + N'WHERE 1 = 1 ' + @sqW + ' '
 
 SET @sq = @sq + N'ORDER BY a.Id'


 -- RESTITUISCE I RISULTATI 
 PRINT @sq
 EXEC sp_executeSql @sq, @paramlist
  , @Stato 
  , @DataDa 
  , @DataA 
  , @Manutentore 


END
GO

30 November 2012

SET ROWCOUNT VS TOP in SQL Server

SET ROWCOUNT statement is marked as Deprecated!!

Both SET ROWCOUNT statement and TOP clause are used to limit the number of rows returned. However there are some significant differences between them. They are listed out here.

SET ROWCOUNT statementTOP clause
It is specific to a batch. It will affect all DML operations until it is reset to 0It has statement level scope and it will not affect other statements until specifiedeach for them
Variable can be used in all version. Ex
SET ROWCOUNT @var
Variable can be used only from version 2005 onwards like TOP (@var)
Not possible to set percentagePossible to set percentage option. Ex
SELECT TOP 20 PERCENT *
FROM TABLE
Not possible to specify decimal valuePossible to specify decimal values along with PERCENT option.
It is executed outside of actual DML and its value is not part of query planThe expression used in TOP clause will be considered as part of query plan.
Multiple SET ROWCOUNT statements are allowed in a single batch. However the lastly available before the statements will be used.
SET ROWCOUNT 10
SET ROWCOUNT 100
SELECT * FROM SYS.OBJECTS
SET ROWCOUNT 0
The COUNT  100 will be considered for execution
Multiple TOP is not allowed however they can be nested.
SELECT TOP 10 * FROM (
    SELECT TOP 100 * FROM SYS.OBJECTS
) AS T
The final result will have maximum of 10 rows
As this is executed as a seperate statement. It can not be part of VIEW definitionIt can be part of VIEW definition.
This is marked as Deprecated. Avoid using thisAlways available in all versions

Trovato qui.

Pinal Dave dice che è una porcheria:

SET ROWCOUNT option is ignored for INSERT, UPDATE, and DELETE statements

Setting the SET ROWCOUNT option causes most Transact-SQL statements to stop processing when they have been affected by the specified number of rows. This includes triggers

27 November 2012

Killare un processo in “arresto in corso” sui sistemi Windows

Mi è capitato oggi di dover litigare con un processo su un server Windows 2008 che, dopo essere stato ritenuto (giustamente) colpevole del blocco della Console “Symantec Endpoint Protection”, ha deciso di freezarsi in quel fastidioso stato che solitamente ci impone un bel riavvio del server.

Essendo tuttavia il server in produzione e non recando il processo bloccato nessun disservizio all’utenza, ho ritenuto eccessivo un reboot a metà mattina.

In sostanza, un metodo per forzare l’arresto di un servizio bloccato in “arresto in corso” o “stop pending” è il seguente:

Anzitutto è necessario il PID del processo da killare, lo possiamo trovare agilmente tramite la console “services.msc”, aprendo le proprietà del servizio bloccato, ne ho aperto uno a caso evidenziando il nome processo univocamente assegnato dal sistema:



Aprire quindi un prompt dei comandi (mi raccomando di usare un account con privilegi di amministrazione), e digitare la seguente riga:

sc queryex "[nomeservizio]"

Appariranno tutta una serie di informazioni carine, tra cui STATO (che sarà “ARRESTO IN CORSO” o “STOP PENDING”) e PID.

Ora digitiamo:

taskkill /F /PID [pid_servizio]

E come per magia il servizio si stopperà.
Per esperienza personale ho riavviato il servizio stesso dopo pochi istanti senza rilevare problema alcuno, e risolvendo anzi il problema iniziale.

Nota importante: verificate che tutti i servizi dipendenti dal servizio in questione siano ancora avviati perchè un kill brutale del servizio padre potrebbe portare alla morte dei servizi figli, senza che il sistema avverta in alcun modo l’utente.

Un sentito ringraziamento per la dritta al collega Cillo.



Testato su Windows Server 2003.
Trovato qiu.

29 October 2012

Copia solo i file più recenti - copia Dump SQL

Option Explicit

Function GetLatestFile(wPath)
   
 Dim fNewest
 dim oFolder
 dim aFile
  
 Set oFolder = CreateObject("Scripting.FileSystemObject").GetFolder(wPath)
 
 For Each aFile In oFolder.Files
     If fNewest = "" Then
         Set fNewest = aFile
     Else
         If fNewest.DateCreated < aFile.DateCreated Then
             Set fNewest = aFile
         End If
     End If
 Next
    
    Set oFolder = nothing
    GetLatestFile = fNewest
    
End Function


Function DumpCopy()

 dim fs 
 dim src
 dim dst
 dim ele(9)
 dim s
 dim wPath
 dim wFrom
 dim wTo

 set fs = createobject("Scripting.FileSystemObject")
 
 src = "\\sqlsrv\c$\Programmi\Microsoft SQL Server\MSSQL10_50.SQL2005\MSSQL\Backup"
 dst = "C:\- DB Dump\GV"
 
 
 ' -- RINOMINA DST DIR
 fs.MoveFolder dst, dst & "_OLD"
 fs.CreateFolder dst

 
 ' -- COPIA I FILE NELL'ELENCO 
 ele(0) = "ASS_VDS"
 ele(1) = "EuroGVen2000"
 ele(2) = "Eurotax"
 ele(3) = "GVSYS"
 ele(4) = "GVxData"
 ele(5) = "ITPortal_RenaultDacia"
 
 for each s in ele
  if s <> "" then
   wPath = src & "\" & s
   wFrom = GetLatestFile(wPath)
   wTo = dst & "\" & fs.GetFile(wFrom).Name
   
   'MsgBox wFrom & vbCrLf & wTo
   fs.CopyFile wFrom, wTo, True
  end if
 next
 
 
 ' -- ELIMINA OLD
 fs.DeleteFolder dst & "_OLD"
 
 set fs = nothing
  
End Function



const cTitle = "Copia dump SQL"

'if MsgBox("Copio i dump?", vbQuestion + vbYesNo, cTitle) = vbYes then
    DumpCopy
    MsgBox "Fatto!", vbInformation, cTitle
'end if

18 October 2012

Install the PyDev plug-in for Eclipse

Path per installazione:
http://pydev.org/updates/

Path Interpreter
Windows:
C:\Program Files\Python32\python.exe
C:\Python27\python.exe
Mac OSX 10.5:
/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7

Plugin Eclipse Color Theme
http://eclipse-color-theme.github.com/update

Qui le istruzioni

15 October 2012

Chrome non si apre

Dopo aver killato i processi di Chrome, l'app non si apre. Se nei log viene visualizzato il seguente errore:
ERROR:process_singleton_mac.cc(106)] Unable to obtain profile lock.

Questa è la soluzione:

I had a similar problem I was able to fix by doing the following: Open Finder, go to ~/Library/Application Support/Google. Move the Chrome folder to the trash and then Chrome will start up! This is kind of a bummer because it will erase all of your settings (you'll even have to reselect your default search provider), but if you have sync set it up, you just turn it back on and it's like nothing ever happened.


Trovato qui.

11 October 2012

SQL 2008 - 2012 - Declare and Assign Variable in Single Statement

Vecchio metodo (dichiarare la variabile e poi settarla):
DECLARE @iVariable INT
DECLARE @vVariable VARCHAR(100)
DECLARE @dDateTime DATETIME

SET @iVariable = 1
SET @vVariable = 'myvar'
SET @dDateTime = GETDATE()

SELECT @iVariable iVar, @vVariable vVar, @dDateTime dDT

Oppure:
DECLARE @iVariable INT; SET @iVariable = 1
DECLARE @vVariable VARCHAR(100); SET @vVariable = 'myvar'
DECLARE @dDateTime DATETIME; SET @dDateTime = GETDATE()

SELECT @iVariable iVar, @vVariable vVar, @dDateTime dDT

Nuovo metodo (.NET-style):
DECLARE @iVariable INT = 1
DECLARE @vVariable VARCHAR(100) = 'myvar'
DECLARE @dDateTime DATETIME = GETDATE()

SELECT @iVariable iVar, @vVariable vVar, @dDateTime dDT

Trovato qui.

Color Coding SQL Server Management Studio Status Bar


Trovato qui.

04 October 2012

NTBackup - errore su nuovo supporto (DAT)

NTBACKUP - errore "Impossibile individuare il supporto o la periferica di backup specificati. L'operazione di backup verrà interrotta."


metti
/um
alla fine della stringa di backup: elimina il controllo della label sul nastro.

http://usenet.it.rooar.com/showthread.php?t=640873



C:\WINDOWS\system32\ntbackup.exe backup "@C:\bks per selezione\selezioni backup.bks" /n "mercoledì" /d "Set creato il 06/09/2012 alle 15.47" /n "mercoledì" /v:yes /r:no /rs:no /hc:on /m normal /j "mercoledì" /l:f /p "4mm DDS" /um


http://ss64.com/nt/ntbackup.html

/um  (Windows 2000 only)

Find the first available media, format it, and use for the current backup.

Use with the /p switch to scan for available media pools. 

This command is only for standalone tape devices (not tape loaders.)

The /UM switch must be at the end of the command line.


http://support.microsoft.com/kb/314844/it




Using Multiple Programming Languages in a Web Site Project

By default, the App_Code folder does not allow multiple programming languages. However, in a Web site project you can modify your folder structure and configuration settings to support multiple programming languages such as Visual Basic and C#. This allows ASP.NET to create multiple assemblies, one for each language.

The App_Code folder is not explicitly marked as containing files written in any one programming language. Instead, the ASP.NET infers which compiler to invoke for the App_Code folder based on the files it contains. If the App_Code folder contains .vb files, ASP.NET uses the Visual Basic compiler; if it contains .cs files, ASP.NET uses the C# compiler, and so on.

 
  
  
 


Trovato qui e qui.

01 October 2012

Get Filename without path/extension

All versions of .Net since 2002 (the first version) has the System.IO.Path namespace that is OS independent, meaning if it's running on Mono (linux or Mac, both of which don't use a "\" as the separater character) it'll still work!
System.IO.Path.GetExtension()
System.IO.Path.GetFileName()
System.IO.Path.GetFileNameWithoutExtension()

Trovato qui.

21 September 2012

Access - evitare l'errore di modifica contemporanea di record

Una form di Access legata ad una tabella SQL via ODBC visualizza questo errore durante il salvataggio:

"Modifica contemporanea di record - Durante la corrente sessione di modifica il record è stato modificato da un altro utente. Salvando le proprie modifiche si sovrascriveranno i cambiamenti dell'altro utente"

Con questo trucco si dovrebbe* evitare l'errore:
ALTER TABLE Table1
ADD Timestamp

La sintassi per la ALTER TABLE (Transact-SQL) dice:

column_name
For new columns, column_name can be omitted for columns created with a timestamp data type. The name timestamp is used if no column_name is specified for a timestamp data type column.

Sostanzialmente aggiunge una colonna di tipo timestamp che si chiama [timestamp] che si aggiorna in automatico.

____

* si dovrebbe = l'ho usato una volta e ha funzionato. =)

06 September 2012

Three Methods to Insert Multiple Rows into Single Table

-- Insert Multiple Values into SQL Server
CREATE TABLE #SQLAuthority (ID INT, Value VARCHAR(100));
Method 1: Traditional Method of INSERT... VALUE
-- Method 1 - Traditional Insert
INSERT INTO #SQLAuthority (ID, Value)
VALUES (1, 'First');
INSERT INTO #SQLAuthority (ID, Value)
VALUES (2, 'Second');
INSERT INTO #SQLAuthority (ID, Value)
VALUES (3, 'Third');

-- Clean up
TRUNCATE TABLE #SQLAuthority;

Method 2: INSERT... SELECT
-- Method 2 - Select Union Insert
INSERT INTO #SQLAuthority (ID, Value)
SELECT 1, 'First'
UNION ALL
SELECT 2, 'Second'
UNION ALL
SELECT 3, 'Third';

-- Clean up
TRUNCATE TABLE #SQLAuthority;
Method 3: SQL Server 2008+ Row Construction
-- Method 3 - SQL Server 2008+ Row Construction
INSERT INTO #SQLAuthority (ID, Value)
VALUES (1, 'First'), (2, 'Second'), (3, 'Third');

-- Clean up
DROP TABLE #SQLAuthority;

Trovato qui.

13 July 2012

Mac OS X Login and Logout Scripts Demystified

Before You Begin

There are some things one must understand about Mac OS X login scripts before you can begin:

Apple refers to them as login- and logout- “hooks”. Hooks run as root so you need to su as the user to take actions as the user. You must activate them with the defaults command or use Workgroup Manager in Open Directory.

Creating a Login Script

You can technically save your scripts anywhere on the filesystem, but /usr/local/bin makes a lot of sense for various reasons.

So, create a file there and mark it executable:
sudo touch /usr/local/bin/login
sudo chmod +x /usr/local/bin/login

Configuring Login Script Actions

Open the login script in your favorite editor:
sudo vi /usr/local/bin/login

Inside the script, you can do things as root or as the user as shown in this sample batch script:
#!/bin/bash
##
# Mac login script
##

# As root, create a directory named "/foo"
mkdir /foo

# As root, set or enforce system settings
defaults write ... 

# As the user, create a directory named "~/foo"
su - $1 -c "/bin/mkdir -p ~/foo"

# As the user, set or enforce user settings
su - $1 -c "/usr/bin/defaults write ..."

The username is passed to the script as the one (and only) argument. In bash, you can use the $1 variable to access the username.

Activating a Login Script

Run this to activate the script:
sudo defaults write com.apple.loginwindow LoginHook /usr/local/bin/login

Logout Scripts

Configure a logout script by following the instructions above then activate it as follows:
sudo defaults write com.apple.loginwindow LogoutHook /usr/local/bin/logout


Trovato qui.



Is there a login hook set on this machine?
sudo defaults read com.apple.loginwindow LoginHook

Add a login hook to MacOS X
sudo defaults write com.apple.loginwindow LoginHook /path/to/script

Remove a login hook in MacOS X
sudo defaults delete com.apple.loginwindow LoginHook /path/to/script

Trovato qui.

15 June 2012

Google Chrome constantly asking for Keychain permission?

Google Chrome on Leopard is asking for access to the keychain when it opens, here's the solution:
Quit Chrome
Open Utilities: Keychain Access
Search for Chrome
Delete "Chrome Safe Storage"
Start up Chrome. Note that Chrome Safe Storage is back in the list.

Trovato qui.

13 June 2012

Regular expression che rimuove tutti i whitespace doppi (tabulatori, ritorni a capo, ecc.):
dim res as String = ""
' rimuove tutti i whitespace [\t\r\n\v\f] doppi
res = Regex.Replace(res, "\s{2,}", "")


Trovato qui.

26 April 2012

SQL Server 2008 - Truncating Transaction Log


DA TESTARE!!!!!!!! --ndBoso


Scenario :


I have a database with the following size
SELECT name,size from sys.database_files


Result
Test 173056
Test_Log 579072 -- 565 MB


Now I want to truncate Transaction log. In earlier version what we do is we truncate the log and shrink the file.
BACKUP LOG Test with Truncate_only

This statement throw an error with below message
/*------------------------
Backup log Test with Truncate_Only
------------------------*/
LHI-115\SQL2008(sa): Msg 155, Level 15, State 1, Line 1
'Truncate_Only' is not a recognized BACKUP option.


The errior is obevious, this command no more exists in SQL Server 2008. So the question is what is the alternative? As per books online “The transaction log is automatically truncated when the database is using the simple recovery model. If you must remove the log backup chain from a database, switch to the simple recovery model.” So this is the one command you should check before migrating to SQL Server 2008. If you have any script which have WITH TRUNCATE_ONLY option then you have to re-write the script.


How to shrink (re-size) the transaction log in SQL Server 2008


As per books online , if you switch the Recovery Model to Simple inactive part of the transaction log should be removed. Let us see what happens


(a) select name,recovery_model_desc from sys.databases
Result
name recovery_model_desc

Test Full

(b) Alter database Test SET Recovery simple

Result
name recovery_model_desc

Test Simple


© select name,size from sys.database_files
Result
Test 173056
Test_Log 451352 -- 440 MB


This process reduced the the transaction log file size. But not to the size what i want. I have no option to set the required size as we had this option in SHRINKFile. Do we need shrink the file after switching the Recovery model? Not sure. I have tested the same database in 2005 and I was able to shrink the file to 1024 KB.

I have tried to shrink the TL after switching the Recovery model and the result is as follows :-
DBCC SHRINKFILE (N'test_log' , 1)

DbId FileId CurrentSize MinimumSize UsedPages EstimatedPages
------ ----------- ----------- ----------- ----------- --------------
6 2 451352 128 451352 128



So.. its obevious that its not shrinking. There is no active transaction in TL, that also i checked.


Note : From my SQL Server 2005 and 2000 server i restored few database in 2008 and tried to Truncate TL. For some database this process worked. others do not. I need to look into it what is the problem with the database which could not shrink.

Summary:


In SQL Server 2008 , Transaction can be shrinked in two step.
(a) Change the Recovery Model to Simple
(c) Shrink the file using DBCC ShrinkFile


Trovato qui.

26 March 2012

Errore su CHECKDB piano manutenzione SQL 2008

Creando un piano di manutenzione (anche con il wizard), il task di DBCC CHECKDB va in errore. Guardando nel log testuale, c'è il seguente messaggio:
[cut]
Operazione non riuscita:(0) Impossibile eseguire Modifica per Server 'SQLSRV2012\\SQL2005'. 
guardando nei log di SQL, c'è invece questo strano messaggio:
Configuration option 'user options' changed from 0 to 0. Run the RECONFIGURE statement to install.
si risolve lanciando questa query:
sp_configure 'Allow Updates', 0



Un po' di documentazione:

http://sqlblog.com/blogs/eric_johnson/archive/2009/12/23/troubleshooting-a-failed-maintenance-plan.aspx

Basically, I ran a profiler trace looking for the User Error Message and Exception events. From the trace, I found this exception:
Error: 5808, Severity: 16, State: 1 
Ad hoc update to system catalogs is not supported.
I then ran sp_configure 'Allow Updates', 0, and ran the package again. Now it succeeded.




Testato su SQL 2008R2 (ma pare fosse un problema anche su 2005).
Trovato qui.

29 February 2012

Cento! Cento! Cento!

E oggi, giorno bisestile, faccio 100! Come a "OK il prezzo è giusto"!    =)

24 February 2012

SQL SERVER – Find Most Expensive Queries Using DMV

This basic script does do the job which I expect to do – find out the most expensive queries on SQL Server Box.
SELECT TOP 10 SUBSTRING(qt.TEXT, (qs.statement_start_offset/2)+1,
((CASE qs.statement_end_offset
WHEN -1 THEN DATALENGTH(qt.TEXT)
ELSE qs.statement_end_offset
END - qs.statement_start_offset)/2)+1),
qs.execution_count,
qs.total_logical_reads, qs.last_logical_reads,
qs.total_logical_writes, qs.last_logical_writes,
qs.total_worker_time,
qs.last_worker_time,
qs.total_elapsed_time/1000000 total_elapsed_time_in_S,
qs.last_elapsed_time/1000000 last_elapsed_time_in_S,
qs.last_execution_time,
qp.query_plan
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
ORDER BY qs.total_logical_reads DESC -- logical reads
-- ORDER BY qs.total_logical_writes DESC -- logical writes
-- ORDER BY qs.total_worker_time DESC -- CPU time

You can change the ORDER BY clause to order this table with different parameters. I invite my reader to share their scripts.

Trovato qui.

03 February 2012

CSS per button Gmail-style

#gmailButton
{ 
 border-radius: 3px;
 -moz-border-radius: 3px;
 background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#ddd));
 background: -moz-linear-gradient(top, #fff, #ddd);  
 border: 1px solid #bbb;
}

13 January 2012

Cross-page postbacks and OnClientClick

This one was asked & replied originally on ASP.NET Forums

You have Button
No matter what you click OK or Cancel, it does a normal postback, as if cross-page postbacks wouldn't exist. Why?

Answer:

Well, cross-page postbacks are implemented using javascript. And when you put return statement like that it ends up into onclick of the rendered button. For example Button like this
renders
As you can see, this effectively prevents rest of the postbacking script from functioning since whatever confirmation box returns, it won't let postback options to be set and therefore prevents cross-page postbacking from working.

Answer is to change confirm check so that it returns only when user click Cancel.

Put the OnClientClick as
OnClientClick ="if ( !confirm('OK?') ) return false;"


Then the rendered onclick attribute changes
onclick="if ( !confirm('OK?') ) return false;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("Button2", "", false, "", "Default4.aspx", false, false))"



And you should be good to go.

Trovato qui.

How to add reference in SSIS / DTSX

Put assembly in
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
OR
C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies
For accessing the dll, generate strong name for assemblies and put in GAC folder
C:\windows\assembly\
Open the Add Reference dialog box again and the assembly should be visibile.


Testato su SQL2005. Trovato qui.

UPDATE!
Sia in SQL2005, che in SQL2008R2 funziona solo se la DLL è messa in
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727