venerdì 24 luglio 2015

Branch on Git

Per scaricare in locale un branch remoto:

git fetch origin branchName
git checkout branchName


Per fare Merge dal master al branch attuale:

git pull
git merge origin master

mercoledì 25 giugno 2014

Creare viste Materializzate in Oracle

Grazie a queste viste è possibile effettuare salvataggi sulle tabelle mostrando direttamente la struttura tramite una vista.
E' fondamentale però che all'interno della vista non vi siano Join, e che le tabelle a cui fa riferimento abbiano una Identity Key.

CREATE MATERIALIZED VIEW TestMaterializedView FOR UPDATE AS 
SELECT ID_GRUPPO, CODICE, TIPO 
FROM Tabella

mercoledì 18 giugno 2014

Compilare viste in MVC

E' possibile abilitare la compilazione delle viste in MVC come descritto in:

in poche parole, nel file di progetto dobbiamo settare questa chiave di configurazione:

 ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  
    true

mercoledì 4 giugno 2014

Effettuare salvataggio su DB con NHibernate durante l'elaborazione




UnitOfWork.CurrentSessionCommitAndRestartTransaction()
sessione = UnitOfWork.GetCurrentSession()

giovedì 20 marzo 2014

Funzione per ricercare un valore testuale specifico in un DataBase

--diabilito output conteggio righe
use database
Set NoCount On

--stringa da cercare ed altre variabili
Declare @strToFind varchar(max) = 'StringaDaCercare'
Declare @stringSchema sysname = ''
Declare @stringTab sysname = ''
Declare @stringListaCampi varchar(Max) = ''
Declare @stringListaCampiDove varchar(Max) = ''
Declare @stringSQL varchar(max) = ''

--elenco tabelle e campi
Declare @Tabs table(
TABLE_SCHEMA sysname
,TABLE_NAME sysname
)

Insert into @Tabs
Select Distinct TABLE_SCHEMA,TABLE_NAME from INFORMATION_SCHEMA.COLUMNS
Where DATA_TYPE in ('char','nchar','varchar','nvarchar')
Order by TABLE_SCHEMA,TABLE_NAME

--ciclo le righe
While 1=1
Begin

         Set @stringListaCampi = ''
         Set @stringListaCampiDove = ''

         Select Top 1 @stringSchema = TABLE_SCHEMA, @stringTab=TABLE_NAME from
@Tabs
         Order by TABLE_SCHEMA,TABLE_NAME;

         --esco su rowcount 0
         IF @@ROWCOUNT=0
         Break;

         --formatto la stringa per la ricerca
         With Fields
         AS
                 (
                 Select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS
                 Where DATA_TYPE in ('char','nchar','varchar','nvarchar','text','ntext')
                 And TABLE_SCHEMA = @stringSchema
                 And TABLE_NAME = @stringTab
                 )

         Select @stringListaCampi = @stringListaCampi + '' +
QUOTENAME(COLUMN_NAME) + ' AS ' + QUOTENAME(COLUMN_NAME) + ',',
         @stringListaCampiDove = @stringListaCampiDove + QUOTENAME(COLUMN_NAME) +
' Like ''%' + @strToFind + '%'' OR '
         From Fields


         Set @stringSQL = 'Select ''' + QUOTENAME(@stringSchema) + ''' As
Table_Schema,''' +    QUOTENAME(@stringTab) + ''' As Table_Name, ' +
Substring(@stringListaCampi,0,LEN(@stringListaCampi))
         + ' from ' + QUOTENAME(@stringSchema) + '.' + QUOTENAME(@stringTab)
         + ' Where ' +
Substring(@stringListaCampiDove,0,LEN(@stringListaCampiDove)-2)

         --eseguo SQL
         Exec(@stringSQL)

         -- elimino la riga dalla tabella temporanea
         Delete From @Tabs
         Where TABLE_SCHEMA = @stringSchema
         And TABLE_NAME = @stringTab

end

lunedì 10 febbraio 2014

Visualizzare la GAC come File System

Per visualizzare la GAC come file system (e eventualmente bypassare eventuali problemi di abilitazione alla scrittura), settare la chiave

DisableCacheViewer = 1 

di tipo: REG_DWORD

in

HKEY_LOCAL_MACHINE > SOFTWARE > Microsoft > Fusion

martedì 4 febbraio 2014

Aprire un Popup da un GridViewCommandColumnCustomButton

Creare il bottone e inserirlo nella colonna,


Dim customE As New GridViewCommandColumnCustomButton
customE.ID = "Nota"
customE.Text = "Aggiungi Nota"
customE.Image.Url = "../imgs/Note.gif"
col.CustomButtons.Add(customE)

gvDocumenti.Columns.Insert(0, col)

e aggiungere il CustomBottonClick gestito per visualizzare il popup.


gvDocumenti.ClientSideEvents.CustomButtonClick = String.Format("function(s, e) {{ if(e.buttonID = 'Sconta') {0}.Show(); }}", "pcSconta")

giovedì 9 gennaio 2014

Popolare un oggetto via Reflection

Per popolare un oggetto (nel suo costruttore) via Reflection utilizzare questo codice:


        public Oggetto(Oggetto obj)
        {
            var fromFields = typeof(Oggetto).GetProperties();
            foreach (var pi in fromFields)
            {
                pi.SetValue(this, pi.GetValue(obj, null), null);
            }
        } 

lunedì 16 settembre 2013

.dll Oracle 64 o 32 bit?

Se necessario per capire che dll abbiamo passato o in generale per capire se dll è 64 bit o 32 bit basta copiarsela sulla propria macchina, lanciare cmd di Visual Studio e fare:
DUMPBIN /headers Oracle.DataAccess.dll

se è 32 bit riceviamo una cosa del genere:
  FILE HEADER VALUES
             14C machine (x86)
             ....


se è 64 bit riceviamo una cosa del genere:
  FILE HEADER VALUES
             8664 machine (x64)
             ....

Ricavare dettaglio Errore in Oracle


Il software vi da un errore Oracle e non potete andare in debug  (o non volete perchè ci vuole troppo), ecco una utile soluzione.
Tacciare gli errori oracle mediante un trigger che si attiva al servererror

create table track_detail (val varchar2(4000));

create or replace procedure track (p_text IN VARCHAR2) IS
  PRAGMA AUTONOMOUS_TRANSACTION;
begin
  insert into track_detail(val)
  values (p_text);
  commit;
end;

create or replace TRIGGER log_err after servererror on schema
DECLARE
  v_temp VARCHAR2(2000) := substr(dbms_utility.format_error_stack,1,2000);
  v_num NUMBER;
  v_sql_text ora_name_list_t;
begin
  v_temp := translate(v_temp,'''','"');
  track(v_temp);
  v_num  := ora_sql_txt(v_sql_text);
  v_temp := null;
  BEGIN
    FOR i IN 1..v_num LOOP
      v_temp := v_temp || v_sql_text(i);
    END LOOP;
  EXCEPTION
    WHEN VALUE_ERROR THEN NULL;
  END;
  v_temp := translate(v_temp,''''||chr(0)||chr(10),'"');
  track(v_temp);
end;

dopo una bella
select * from track_detail

vi fornirà errore e select che l'applicativo vuole richiamare e la potete lanciare da un query browser o altro ide.

Attenzione: Eliminare dopo l'uso il trigger e la tabella
drop trigger LOG_ERR;

drop table TRACK_DETAIL;

mercoledì 21 agosto 2013

Popolare un TreeView con un DataTable

Per Popolare dinamicamente un TreeView da un DataTable utilizzare questa classe, richiamabile con 

CreateTreeViewFromDataTable.BuildTree(dt, tvSchedeCollegate, True, "Testo", "IdScheda", "IdPadre")



Class CreateTreeViewFromDataTable
    ' This Dictionary will identify each List<TreeNode>
    ' And the List<TreeNode> will restore the all TreeNode from a same parentNode
    Private Shared dic As Dictionary(Of Integer, List(Of TreeNode))

    Public Shared Sub BuildTree(ByVal dt As DataTable, ByVal treeView As TreeView, ByVal expandAll As [Boolean], ByVal displayName As String, ByVal nodeId As String, ByVal parentId As String)
        ' Clear the TreeView if there are another datas in this TreeView
        treeView.Nodes.Clear()

        dic = New Dictionary(Of Integer, List(Of TreeNode))()

        Dim node As TreeNode = Nothing

        For Each row As DataRow In dt.Rows

            ' Restore each record into a TreeNode
            node = New TreeNode(row(displayName).ToString())
            node.Tag = row(nodeId)
            node.BackColor = Color.FromArgb(row("Colore"))
            ' The parentId of the TreeView's root is "" in the DataTable
            ' So if the parentId is a "", then it is the root
            ' Otherwise it is only a common TreeNode
            If row(parentId).ToString() <> "0" Then
                Dim _parentId As Integer = Convert.ToInt32(row(parentId))

                ' If there's exists a List<TreeNode> was identified by this _parentId
                ' Then we need put this node into this identified List<TreeNode>
                If dic.ContainsKey(_parentId) Then
                    dic(_parentId).Add(node)
                Else
                    ' Otherwise
                    ' We will Add a new record into the Dictionary<int, List<TreeNode>>
                    dic.Add(_parentId, New List(Of TreeNode)())

                    ' Then put this node into the new List<TreeNode>
                    dic(_parentId).Add(node)
                End If
            Else
                ' Take this node into the place of the TreeView's root
                node.NodeFont = New Font(treeView.Font, FontStyle.Bold)
                node.BackColor = Color.FromArgb(row("Colore"))
                node.Text = "[" & row("DesSpeciale") & "]" & vbTab & vbTab & node.Text
                treeView.Nodes.Add(node)
            End If
        Next

        ' After collect and identify each collection with their parentId
        ' We will go on building this tree with the founded root node
        SearchChildNodes(treeView.Nodes(0))

        If expandAll Then
            ' Expand the TreeView
            treeView.ExpandAll()
        End If
    End Sub

    Private Shared Sub SearchChildNodes(ByVal parentNode As TreeNode)

        If Not dic.ContainsKey(Convert.ToInt32(parentNode.Tag)) Then
            ' If there's no a identified collection by this parentId
            ' We will do nothing and return directly
            Return
        End If

        ' Put the identified collection by this parentId into the tree as this node's children
        parentNode.Nodes.AddRange(dic(Convert.ToInt32(parentNode.Tag)).ToArray())

        ' See these children nodes as parent nodes
        For Each _parentNode As TreeNode In dic(Convert.ToInt32(parentNode.Tag)).ToArray()
            ' Then go to find the identified collection by these id
            SearchChildNodes(_parentNode)
        Next
    End Sub
End Class

martedì 9 luglio 2013

Creare un report in PDF ed inviarlo per e-mai

Per Creare un report in PDF ed inviarlo per e-mail utilizzare il seguente  codice:




    Public Sub ExecManutenzione(isTest As Boolean)
        Try
            Dim report As New ReportDocument
            report.Load("ReportFile")

            report.SetDatabaseLogon("DatabaseUser", "DatabasePassword", "DatabaseServer", "DatabaseDb")

            report.SetParameterValue("@Data", DateTime.Now)
            SendEmail("AddressFrom", "AddressTo", "Report", "In Allegato il report", report, "fileName.pdf")
          
        Catch ex As Exception
            Common.Utility.Log("Nel ExecManutenzione " & vbCrLf & ex.Message)
        End Try
    End Sub

    Public Sub SendEmail(AddressFrom As String, AddressTo As String, subject As String, body As String, rpt As ReportDocument, fileName As String)
        Try
            Dim mm As New MailMessage()
            mm.From = New MailAddress(AddressFrom)

            Dim destinatari As String() = AddressTo.Split(";")
            For Each destinatario As String In destinatari
                mm.To.Add(destinatario)
            Next

            'mm.[To].Add(New MailAddress(AddressTo, "To Name"))
            mm.Subject = subject
            mm.Body = body
            mm.Attachments.Add(New Attachment(rpt.ExportToStream(ExportFormatType.PortableDocFormat), fileName))

            Dim sc As New SmtpClient
            sc.Send(mm)
        Catch ex As Exception
            Common.Utility.Log("Nel SendEmail " & vbCrLf & ex.Message)
        End Try
    End Sub



giovedì 18 aprile 2013

Installare il framework 4 su IIS 7.


%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
If I had been on a 32 bit system, it would have looked like the following:
%windir%\Microsoft.NET\Framework\v4.0.21006\aspnet_regiis.exe -i

mercoledì 10 aprile 2013

Scrivere risultato query in riga separato da virgola


Select *
      , STUFF(
         (
           select ', ' +  titIngrediente
     from tbingredienti
    where titIngrediente.idProdotto = TbProdotti.idProdotto
  FOR XML PATH('')
         ), 1, 1, ''
       ) AS [accessories]
FROM [TbProdotti]

giovedì 4 aprile 2013

Disabilitare compatibilità di Internet Explorer

Per disabilitare la compatibilità di Internet Explorer aggiunere:
1. Master Page


<head>
   <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
</head>


2. nel Web.config
<system.webServer>
  <httpProtocol>
    <customHeaders>
      <clear />
      <add name="X-UA-Compatible" value="IE=Edge" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

martedì 29 gennaio 2013

Castare un DateTime in formato Date

(SELECT CONVERT(VARCHAR(10), pn_datreg, 103) AS [DD/MM/YYYY]) as datreg

lunedì 28 gennaio 2013

UpdateProgress

E' possibile utilizzare un UpdateProgress abbinato all' UpdatePanel per fare in modo di visualizzare un'immagine di "attesa" durante il caricamento del pannello.



<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
      <div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
        <asp:Image ID="imgUpdateProgress" runat="server" ImageUrl="images/ajax-Progress.gif" AlternateText="Attendere prego..." ToolTip="Attendere prego..." style="padding: 10px;position:fixed;top:45%;left:50%;" />
     </div>
</ProgressTemplate>
</asp:UpdateProgress>  
 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
    </ContentTemplate>
</asp:UpdatePanel>



E' possibile personalizzare l'immagine visualizzata creandola da questo portale:

http://www.ajaxload.info/

giovedì 24 gennaio 2013

Scatenare l'evento postback all'interno di un UpdatePanel

Per far in modo che un elemento all'interno di un UpdatePanel scateni un postback, aggiungere queste righe nel Page_Load


        Dim scriptManager As ScriptManager = scriptManager.GetCurrent(Me.Page)
        scriptManager.RegisterPostBackControl(btnFattura)


Se invece abbiamo la necessità di far scatenare un evneto JavaScript dal CodeBehind è necesserio utilizzare questa procedura:


        Dim ObjScript As String = "openWinINFO('" & Nota & "');"
        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), Guid.NewGuid().ToString(), ObjScript, True)

lunedì 21 gennaio 2013

TRY CATCH in Sql Server


Con questa procedura è possibile intercettare un particolare errore (in questo caso un Deadlock), e rieseguire la procedura richiesta, per un determinato numero di volte (per evitare un loop)
DECLARE @RetryCounter INT
SET @RetryCounter = 1
RETRY: -- Label RETRY
BEGIN TRANSACTION
BEGIN TRY

 UPDATE Customer SET LastName = 'John' WHERE CustomerId=111
 

 COMMIT TRANSACTION
END TRY
BEGIN CATCH
 PRINT 'Rollback Transaction'
 ROLLBACK TRANSACTION
 DECLARE @DoRetry bit; -- Whether to Retry transaction or not
 DECLARE @ErrorMessage varchar(500)
 SET @doRetry = 0;
 SET @ErrorMessage = ERROR_MESSAGE()
 IF ERROR_NUMBER() = 1205 -- Deadlock Error Number
 BEGIN
  SET @doRetry = 1; -- Set @doRetry to 1 only for Deadlock
 END
 IF @DoRetry = 1
 BEGIN
  SET @RetryCounter = @RetryCounter + 1 -- Increment Retry Counter By one
  IF (@RetryCounter > 3) -- Check whether Retry Counter reached to 3
  BEGIN
   RAISERROR(@ErrorMessage, 18, 1) -- Raise Error Message if 
    -- still deadlock occurred after three retries
  END
  ELSE
  BEGIN
   WAITFOR DELAY '00:00:00.05' -- Wait for 5 ms
   GOTO RETRY -- Go to Label RETRY
  END
 END
 ELSE
 BEGIN
  RAISERROR(@ErrorMessage, 18, 1)
 END
END CATCH

mercoledì 2 gennaio 2013

leggere un valore dalla radgrid on ItemCommand


Protected Sub RadGrid1_ItemCommand(ByVal source As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.ItemCommand

        Dim action As String = e.CommandName

        If (action = "XXX") Then

            Dim id As Integer = e.CommandArgument

            Dim item As GridItem = DirectCast(e.Item, GridItem)
            ' definire l'oggetto da leggere
            Dim campo As HiddenField = DirectCast(DirectCast(item, Telerik.Web.UI.GridDataItem).FindControl("hiddenCampo"), HiddenField)

            'definire il tipo di dato i uscita
            Dim valore As String = campo.Value

        End If

    End Sub