26 October 2009

Embedding JW FLV Media Player in ASP.Net forms

Recent days I got a project with requirement to play flv video, so I found an free for non commecrial purposes flv player, but the problem that I had was how to find way to "control" what the player is going to play by the users' choise. So what I needed was to "inject" this javascript embedded player dynamically into pages' html, that way I got the power to control what is going to be passed to and played by the player (I've used url query string to pass videos' file name to the player as parameter).
What I did in aspx file was to put holder for the javascript player code:
<asp:PlaceHolder ID="PlaceHolder1" runat="server" />
Then I used HtmlGenericControl to "inject" the javascript player code into holder:
Dim Span As New HtmlControls.HtmlGenericControl("span")
   Span.Attributes.Add("style", "z-index: 80")
   Span.InnerHtml = "<a id=""container"" href="" http://www.macromedia.com/go/getflashplayer""></a>" & _
"<script type=""text/javascript"" src=""swfobject.js""></script>" & _
"<script type=""text/javascript"">" & _
"var s = new SWFObject(""mediaplayer.swf"",""mediaplayer"",""" & "400" & """,""" & "300" & """,""" & "8" &""");" & _
"s.addParam(""allowfullscreen"",""true"");" & _
"s.addVariable(""width"",""" & "400" & """);" & _
"s.addVariable(""height"",""" & "300" & """);" & _
"s.addVariable(""file"",""" & "" & Request.QueryString("filename") & ".flv" & """);" & _
"s.addVariable(""image"",""" & "" & """);" & _
"s.addParam(""wmode"", ""transparent"");" & _
"s.write(""container"");" & _
"</script>"
   PlaceHolder1.Controls.Add(Span)

Tips on Optimizing Your Queries

The next few paragraphs will attempt to give you a few rudimentary rules for speeding up your queries in general, and especially how SQLite is adversely affected by the kinds of SQL behaviors you may have taken for granted in other providers. It is by no means a complete optimization guide. For even more details on optimizing your queries, visit sqlite.org.
The Importance of Transactions

If you are inserting data in SQLite without first starting a transaction: DO NOT PASS GO! Call BeginTransaction() right now, and finish with Commit()! If you think I'm kidding, think again. SQLite's A.C.I.D. design means that every single time you insert any data outside a transaction, an implicit transaction is constructed, the insert made, and the transaction destructed. EVERY TIME. If you're wondering why in the world your inserts are taking 100x longer than you think they should, look no further.
Prepared Statements

Lets have a quick look at the following code and evaluate its performance:

      using (SQLiteCommand mycommand = new SQLiteCommand(myconnection))
      {
        int n;
        
        for (n = 0; n < 100000; n ++)
        {
          mycommand.CommandText = String.Format("INSERT INTO [MyTable] ([MyId]) VALUES({0})", n + 1);
          mycommand.ExecuteNonQuery();
        }
      }

This code seems pretty tight, but if you think it performs well, you're dead wrong. Here's what's wrong with it:

  • I didn't start a transaction first! This insert is dog slow!
  • The CLR is calling "new" implicitly 100,000 times because I am formatting a string in the loop for every insert
  • Since SQLite precompiles SQL statements, the engine is constructing and deconstructing 100,000 SQL statements and allocating/deallocating their memory
  • All this construction and destruction is involving about 300,000 more native to managed interop calls than an optimized insert

So lets rewrite that code slightly:

      using (SQLiteTransaction mytransaction = myconnection.BeginTransaction())
      {
        using (SQLiteCommand mycommand = new SQLiteCommand(myconnection))
        {
          SQLiteParameter myparam = new SQLiteParameter();
          int n;
        
          mycommand.CommandText = "INSERT INTO [MyTable] ([MyId]) VALUES(?)";
          mycommand.Parameters.Add(myparam);
          
          for (n = 0; n < 100000; n ++)
          {
            myparam.Value = n + 1;
            mycommand.ExecuteNonQuery();
          }
        }
        mytransaction.Commit();
      } 

Now this is a blazing fast insert for any database engine, not just SQLite. The SQL statement is prepared one time -- on the first call to ExecuteNonQuery(). Once prepared, it never needs re-evaluating. Furthermore, we're allocating no memory in the loop and doing a very minimal number of interop transitions. Surround the entire thing with a transaction, and the performance of this insert is so far and away faster than the original that it merits a hands-on-the-hips pirate-like laugh.

Every database engine worth its salt utilizes prepared statements. If you're not coding for this, you're not writing optimized SQL, and that's the bottom line.

22 October 2009

SQL SERVER – Forgot the Password of Username SA

Resetting the password of SA is a breeze!

Option 1 :

If there is any other SQL Server Login that is a member of sysadmin role, you can log in using that account and reset the password of SQL Server. Change the password of SA account as described here :  SQL SERVER – Change Password of SA Login Using Management Studio.

Option 2 :

If there is any other Windows Login that is a member of Windows Admin Group, log in using that account. Start SQL Server in Single User Mode as described here :  SQL SERVER – Start SQL Server Instance in Single User Mode.
Create a new login and give it sysadmin permission.

Note : If you have SQL Server Agent enabled, it starts before SQL Server service. If you have enabled SQL Server in a single user mode, it will connect it first, so it is recommended to turn that off before attempting any of the above options.

Trovato qui.

16 October 2009

Trova le tabelle con Foreign Keys

SELECT f.name AS ForeignKey,
OBJECT_NAME(f.parent_object_id) AS TableName,
COL_NAME(fc.parent_object_id,
fc.parent_column_id) AS ColumnName,
OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
COL_NAME(fc.referenced_object_id,
fc.referenced_column_id) AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id

Trova tabelle senza Primary Key

SELECT DISTINCT [TABLE] = OBJECT_NAME(OBJECT_ID)
FROM SYS.INDEXES
WHERE INDEX_ID = 0
AND OBJECTPROPERTY(OBJECT_ID,'IsUserTable') = 1
ORDER BY [TABLE]

15 October 2009

Se non funziona il BACKSPACE nell'editor di testo di Visual Studio 2005

Elimnare i files *.vsk nella directory:
"c:\Documents and Settings\francesco.bosetti\Dati applicazioni\Microsoft\VisualStudio\8.0\"
non so cosa siano di preciso... :)

14 October 2009

BosoEstractHere.vbs

Programma per estrarre e aprire un file compresso:
Option Explicit
' REL. 2009-03-30

'-- PARAMETERS --------------------------------------------------------------------
const zipperName = "\TUGZip\TUGZip.exe"
const zipperPara = "e"
'----------------------------------------------------------------------------------


'-- CONSTANTS ---------------------------------------------------------------------
const runWindowStyleMin = 2
const runWindowStyleMax = 3
const runWindowStyleActivate = 5
const runWaitOnReturn = True	' lo script deve aspettare che l'istruzione termini 
                                ' prima di continuare?
'----------------------------------------------------------------------------------


dim fso, wsh


set fso = CreateObject("Scripting.FileSystemObject")
set wsh = CreateObject("WScript.Shell")


' get script parameters
dim argFile
argFile = WScript.Arguments(0)


' get curent zip_filename
dim curFile
curFile = fso.GetBaseName(argFile)


' get filename dir
dim curDir
curDir = fso.GetParentFolderName(argFile) 
if Right(curDir, 1) <> "\" then curDir = curDir & "\"


' create new directory using dir+filename(w/o extension)
dim newDir
newDir = curDir & curFile

if not fso.FolderExists(newDir) then
	fso.CreateFolder(newDir)
end if


' finds programs directory
dim progDir
progDir = wsh.Environment("PROCESS").Item("ProgramFiles")





' shell launch unzipper
dim wCmd
wCmd = ""
wCmd = wCmd & Chr(34) & progDir & zipperName & Chr(34) & " "
wCmd = wCmd & Chr(34) & zipperPara & Chr(34) & " "
wCmd = wCmd & Chr(34) & argFile & Chr(34) & " "
wCmd = wCmd & Chr(34) & newDir & Chr(34)

wsh.run wCmd, runWindowStyleMax, runWaitOnReturn




' -- move the folder up one level ---------------------------------------------
Dim wrongDir
Dim rightDir

wrongDir = newDir & "\" & curFile
rightDir = curDir & curFile
Const tempDir = "tmp.boso"


If fso.FolderExists(wrongDir) Then
    'MsgBox wrongDir & vbCrLf & rightDir
    fso.MoveFolder wrongDir, tempDir
    fso.DeleteFolder rightDir, True
    fso.MoveFolder curDir & tempDir, rightDir
End If
' -----------------------------------------------------------------------------




' open folder
wsh.Run "explorer " & Chr(34) & newDir & Chr(34), 5, runWaitOnReturn






set wsh = nothing
set fso = nothing

BosoScriviEnviron.vbs

Codice per scrivere una variabile d'ambiente:
dim wsh, e
dim varName
dim valoreDaScrivere

with Wscript
	varName = .Arguments(0)
	valoreDaScrivere = .Arguments(1)
end with


set wsh = CreateObject("WScript.Shell")
with wsh
	Set e = .Environment("USER")
	e(varName) = valoreDaScrivere
	set e = nothing
end with

set wsh = nothing

BosoNewFolder.vbs

Codice per creare una nuova cartella random e aprirla:
Option Explicit

Function GeneratePassword(strCharacters, intLength)
	
	Randomize
	Dim strS, intI
	
	For intI = 1 To intLength
		strS = strS + Mid(strCharacters, Int(Rnd() * Len(strCharacters))+1, 1)
	Next
	
	GeneratePassword=strS
	
End Function

Sub CreateNewFolder(baseFolder)
	
	const allowedChars = "abcdefgijklmnopqrstuvwxyz"
	const nameLength = 4
	
	
	const tempFolder = 2
	const runWaitOnReturn = True	' lo script deve aspettare che l'istruzione termini 
									' prima di continuare?
								
	dim fullPath
	dim fso
	dim wsh
	
	set wsh = CreateObject("WScript.Shell")

	
	set fso = CreateObject("Scripting.FileSystemObject")
	
	' genera un nome casuale che non esista
	fullPath = fso.GetSpecialFolder(tempFolder)
	
	while fso.FolderExists(fullPath)
		fullPath = GeneratePassword(allowedChars, nameLength)
	wend
	
	' normalizza la stringa
	fullPath = UCase(Left(fullPath, 1)) & Right(fullPath, Len(fullPath) - 1)
	
	' compone il path completo
	if right(baseFolder, 1) <> "\" then baseFolder = baseFolder & "\"
	fullPath = baseFolder & fullPath
	
	' crea directory
	fso.CreateFolder(fullPath)
	
	' open folder
	wsh.Run "explorer " & Chr(34) & fullPath & Chr(34), 5, runWaitOnReturn

	set wsh = nothing
	set fso = nothing
	
End Sub

CreateNewFolder(wscript.arguments.item(0))

BosoMailToMe.wsf

Ecco come inviare email da VBScript:








Specificare la stringa di connessione con path relativo nel web.config di ASP.NET 2.0

ASP.NET 2.0 ha una nuova sezione di configurazione pensata apposta per lo storage delle stringhe di connessione. Quello che è interessante è la possibilità di inserire i propri database (nel caso di Access o SQL Server 2005 Express, che lavorano con un file fisico) nella directory App_Data, di sistema, e poi specificare |DataDirectory| nella stringa di connessione, in modo che venga in automatico risolto il percorso locale, a prescindere da dove si trova effettivamente la directory:
 
   
      
   
Per leggere la stringa di connessione sarà poi sufficiente un codice come il suguente:
string connstring = ConfigurationManager.ConnectionStrings["Access.Pubs"].ConnectionString;
di Daniele Bochicchio, 24 aprile 2006

UrlMappings da web.config con ASP.NET 2.0

Una delle tante comodità introdotte con ASP.NET 2.0 è l'urlMappings, ossia nascondere un parametro dall'url, in modo da migliorare l'indicizzazione ai motori di ricerca e di evitare l'indirizzo completo nella barra url del browser. Con la versione 2.0 questa procedura è stata semplificata dando la possibilità allo sviluppatore di inserire nel file web.config un tag urlMappings dove andare ad inserire gli indirizzi da intercettare e quelli mappati. Il codice seguente mostra come fare:
 
   
     
   
L'attributo url indica l'indirizzo che verrà visualizzato nella barra del browser, mentre quello mappedUrl indica l'indirizzo a cui corrisponde veramente la pagina. In questo esempio dalla pagina default.aspx sarà possibile recuperare il parametro id senza che venga visualizzato nella barra degli indirizzi. Ovviamente questo non è il metodo ideale per un'applicazione di un certo livello, dove è consigliato utilizzare un HttpHandler, ma sicuramente è comodo per piccole applicazioni con un numero fisso e limitato di pagine. di Ugo Lattanzi, 21 giugno 2006

13 October 2009

Ottenere l'ouput di una shell

Dim oSh, oEx, OS

Set oSh = CreateObject("WScript.Shell")
Set oEx = oSh.Exec("%COMSPEC% /C ver")

Do While oEx.Status = 0
	WScript.Sleep 100
Loop

While Len(os) < 1
	os = Replace(oEx.StdOut.ReadLine, vbCrLf, "")
Wend

WScript.Echo "OS = " & os

Ottenere una lista in italiano dei mesi dell'anno

VB.NET
    For i As Integer = 1 To 12
      Dim s As String = New DateTime(DateTime.Now.Year, i, 1).ToString("MMMM", _
                                     New System.Globalization.CultureInfo("it-IT"))
      System.Diagnostics.Debug.WriteLine(s)
    Next
C#
      for (int i = 1; i < 13; i++)
      {
         string s = new DateTime(DateTime.Now.Year,i,1).ToString("MMMM",
                                 new System.Globalization.CultureInfo("it-IT"));
         System.Diagnostics.Debug.WriteLine(s);
      }

Leggere i contatti di Outlook

' Nei Riferimenti del progetto importare :  Microsoft.Office.Interop.Outlook
Imports Outlook = Microsoft.Office.Interop.Outlook
  Sub LeggeContatti()
    ' Crea Outlook application.
    Dim olApp As Outlook.Application = New Outlook.Application
    ' Legge la carella dei contatti.
    Dim olMapi As Outlook.NameSpace = olApp.GetNamespace("MAPI")
    Dim olContacts As Outlook.MAPIFolder = olMapi.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts)
    ' Legge il primo contatto dalla cartella Contacts
    Dim olMailItems As Outlook.Items = olContacts.Items
    Dim olContact As Outlook.ContactItem
    olContact = TryCast(olMailItems.GetFirst(), Outlook.ContactItem)
    Do While olContact IsNot Nothing
      ' Queste alcune proprietà di Outlook.ContactItem
      Console.WriteLine(olContact.FullName)
      Console.WriteLine(olContact.Title)
      Console.WriteLine(olContact.Birthday)
      Console.WriteLine(olContact.CompanyName)
      Console.WriteLine(olContact.Department)
      Console.WriteLine(olContact.Body)
      Console.WriteLine(olContact.FileAs)
      Console.WriteLine(olContact.Email1Address)
      Console.WriteLine(olContact.BusinessHomePage)
      Console.WriteLine(olContact.MailingAddress)
      Console.WriteLine(olContact.BusinessAddress)
      Console.WriteLine(olContact.OfficeLocation)
      Console.WriteLine(olContact.Subject)
      Console.WriteLine(olContact.JobTitle)
      olContact = TryCast(olMailItems.GetNext(), Outlook.ContactItem)
    Loop
    ' Clean up.
    olApp = Nothing
    olMailItems = Nothing
    olContact = Nothing
  End Sub

Sapere dove è utilizzato un metodo con Visual Studio

Un modo semplice e "fatto in casa" per sapere dove viene utilizzato un metodo nel progetto corrente, senza far uso di addin specifici, è quello di marcare la procedura con l'attributo <Obsolete()>. Così facendo Visual Studio ne elencherà nei warnings tutte le chiamate presenti nel progetto:
<Obsolete()> _
Public Function LaMiaFunzione() As String
    '...
End Function
Autore: Antonio (tdj) Catucci
Data pubblicazione: 31/03/2009 20.19.35
Trovato qui