Sei sulla pagina 1di 13

Creazione Infrastruttura Virtuale Documento di Test

Indice generale
1. Query SQL Maschere.....................................................................................................................1 2. Elenco Query/Script da eseguire...................................................................................................2 3. Recupero valori da Gridview Field e HiddenField......................................................................3 4. Inserire il numero di record...........................................................................................................4 5. Inviare e recuperare parametri da querystring...........................................................................4 6. Codice bottone Search....................................................................................................................6 7. Una ricerca completa......................................................................................................................7 7. Uso del coalesce per ottenere una stringa completa da colonna tabella....................................9

iii

iv

1. Infrastruttura
L'infrastruttura che verr creata far parte del dominio andrea.local.

2. Elenco Query/Script da eseguire


Per poter usare il calendario usare ajaxToolkit
<asp:TextBox CssClass="textBoxData" runat="server" ID="txtPlannedAt" /> <ajaxToolkit:CalendarExtender ID="CalendarPlannedAt" runat="server" Enabled ="True" TargetControlID="txtPlannedAt" CssClass="MyCalendar" FirstDayOfWeek = "Monday" Format="dd/MM/yyyy" PopupButtonID="imgPlannedAt" /> <asp:Image runat="server" ID="imgPlannedAt" ImageUrl="~/Images/calendar_month.png"/> <asp:CustomValidator ID="cvPlannedAt" runat="server" ErrorMessage='<%$ Resources:Localization, ERROR_InvalidDate%>' ValidationGroup="InitiativeListValidate" ControlToValidate="txtPlannedAt" ValidateEmptyText="false" OnServerValidate="cvPlannedAt_ServerValidate"> </asp:CustomValidator>

Viene fatto click sull'immagine associata al calendarietto e cos si apre il popup relativo. Il validatore un customValidator e ha bisogno della seguente funzione personalizzata che valida la data
protected void cvPlannedAt_ServerValidate(object source, ServerValidateEventArgs args)
{

bool retValue = true; DateTime d; if(!DateTime.TryParse(txtPlannedAt.Text, out d))


{

txtPlannedAt.Text = "";
}

if (!(DateTimeFormatter.IsDateTime(txtPlannedAt.Text)))
{

cvPlannedAt.ErrorMessage =

Resources.Localization.ERROR_InvalidDateField; retValue = false;


} args.IsValid = retValue;

} Il validatore permette di validare una data in formato gg/mm/aaaa se per caso viene scritto CICCIO allora

non verr validato nulla.

3. Recupero valori da Gridview Field e HiddenField


Per poter recuperare valori da gridview necessario eseguire la funzione FindControl. Ecco il caso per un campo nascosto in griglia :
GridViewRow row = (sender as ImageButton).Parent.Parent as GridViewRow;

e prendere :
HiddenField hdfInitiativeCode = (HiddenField)row.FindControl("hdfInitiativeCode"); initiativecode = hdfInitiativeCode.Value;

invece per un campo non nascosto : string message = (string)row.FindControl(message); Per recuperare da code behind un valore di una dropdownlist invece :
responsible = ddlResponsible.SelectedValue.ToString();

4. Inserire il numero di record


Per poter inserire il numero di record necessario inserire due label con allieneamento a destra e fare l'overload del metodo di objectdatasource onSelected=odsInitiativesList_Selected
protected void odsInitiativesList_Selected(object sender, ObjectDataSourceStatusEventArgs e) { int recordCount = ((DataTable)e.ReturnValue).Rows.Count; NrRecords = recordCount.ToString(); lblRecordCount.Visible = (recordCount != 0); lblRecordCountValue.Visible = (recordCount != 0); lblRecordCountValue.Text = NrRecords; }

e definire NELLA GRIDVIEW (non nell'objectdataSource)

OnDataBound="gdvInitiativesList_DataBound"
protected void gdvInitiativesList_DataBound(object sender, EventArgs e) { this.lblRecordCountValue.Text = NrRecords; }

5. Inviare e recuperare parametri da querystring


Per poter inviare parametri ad una pagina necessario usare il Response.write e costruire la querystring,.
QueryString = "InitiativeCode=" + initiativecode + "&Title=" + title + "&Responsible=" + responsible + "&InitiativeTarget=" + initiativetarget + "&LdmCode=" + ldmcode + "&PlannedDate=" + planneddate + "&InitiativeStatus=" + initiativestatus + "&StatusOfCentralization=" + statusofcentralization; Response.Redirect("NpsInitiativeManagement.aspx?" + QueryString);

Per poterli ricevere invece nel PageLoad bisogna fare cos :


protected void Page_Load(object sender, EventArgs e) { if (!(Page.IsPostBack)) { UserCode = CurrentApplicationUserHolder.CurrentApplicationUser.UserCode; //Etichetta di debug... lblUserCode.Text = UserCode; bool showFilterSection = false; txtTitle.Text = string.Empty; txtPlannedAt.Text = string.Empty; ddlResponsible.DataBind(); ddlScope.DataBind(); ddlStatusOfInitiative.DataBind();

ddlStatusOfCentralization.DataBind(); ddlLdm.DataBind(); // Recupero i valori passati dalla pagina di dettaglio if (!(string.IsNullOrEmpty(Request.QueryString["Title"]))) { txtTitle.Text = Request.QueryString["Title"].ToString(); showFilterSection = true; } if (! (string.IsNullOrEmpty(Request.QueryString["Responsible"]))) { Responsible = Request.QueryString["Responsible"].ToString(); for (int i = 0; i < ddlResponsible.Items.Count; i++) { if (ddlResponsible.Items[i].Value == Responsible) { ddlResponsible.SelectedIndex = i; ddlResponsible.Items[i].Selected = true; break; } } showFilterSection = true; } //questo parametro siamo sicuri arriva.... LdmCode = Request.QueryString["LdmCode"]; for (int i = 0; i < ddlLdm.Items.Count; i++) { if (ddlLdm.Items[i].Value == LdmCode) { ddlLdm.SelectedIndex = i; ddlLdm.Items[i].Selected = true; break; } } // Se lo stato 0 allora chiudo il pannello if (ddlLdm.SelectedIndex != 0) { showFilterSection = true; } odsInitiativesList.DataBind(); updpnlNrRecord.Update();

if (showFilterSection) { ShowFilter(); }

6. Codice bottone Search


protected void btnSearch_Click(object sender, EventArgs e)
{

if (Page.IsValid)
{ odsInitiativesList.DataBind(); gdvInitiativesList.DataBind(); updpnlNrRecord.Update(); updpnInitiativesList.Update(); }

7. Una ricerca completa


ALTER PROCEDURE [dbo].[GetEmployee] @CodCompany ,@Surname ,@Name ,@BirthDateEnd ,@Active ,@SupervisorId AS BEGIN SELECT tbEmployee.CodResource ,tbEmployee.CodCompany ,tbEmployee.Surname int varchar(255) varchar(50) DateTime int int

,@BirthDateStart DateTime

,tbEmployee.Name ,tbCompanies.CompanyName ,tbEmployee.BirthDate ,tbEmployee.Active ,tbSupervisors.SuperVisorId ,tbSupervisors.SupervisorName FROM tbEmployee INNER JOIN tbCompanies ON tbEmployee.CodCompany = tbCompanies.CodCompany LEFT OUTER JOIN tbSuperVisors ON tbEmployee.SuperVisorId = tbSuperVisors.SuperVisorId WHERE ((tbEmployee.Active = @Active ) OR @Active = -1) -- Campi testuali AND (tbEmployee.Surname LIKE AND (tbEmployee.Name LIKE AND + '%' + @Surname + '%' OR @Surname IS NULL) ,tbEmployee.BirthDate) ,tbEmployee.BirthDate)) + '%' + @Name + '%' OR @Name IS NULL) ISNULL(@BirthDateStart ISNULL(@BirthDateEnd AND ((tbEmployee.CodCompany = @CodCompany ) OR @CodCompany = 0)

AND (tbEmployee.BirthDate BETWEEN

AND (tbSupervisors.SupervisorId = @SupervisorId OR (tbEmployee.SupervisorId IS NULL AND @SupervisorId IS NULL ) OR (@SupervisorId = 0)) ORDER By tbEmployee.Surname,tbEmployee.Name,tbEmployee.BirthDate END

La maschera la seguente :

((tbEmployee.CodCompany = @CodCompany ) OR @CodCompany = 0)

AND (tbSupervisors.SupervisorId = @SupervisorId OR (tbEmployee.SupervisorId IS NULL AND @SupervisorId IS NULL ) OR (@SupervisorId = 0))

In questa linea di codice si specifica una scelta puntuale OPPURE una scelta nulla (ossia il valore a database nullo e la scelta effettuata nulla) oppure la scelta a 0. Una alternativa alla seconda poteva essere :
(ISNULL(tbEmployee.SupervisorId,'') = '' AND @SupervisorId IS NULL) OR SupervisorId non valorizzato. -- con

7. Uso del coalesce per ottenere una stringa completa da colonna tabella
-- CODICE SQL PER COMPATTARE UNA TABELLA ALTER FUNCTION dbo.ChoiceToString ( @CodResource varchar(15) ) RETURNS varchar(Max) AS BEGIN DECLARE SELECT FROM @result varchar(max) @result = coalesce(@result + ',', '') + SpecializationId tbImpSpec

WHERE END

tbImpSpec.CodResource = @CodResource

RETURN @result

DECLARE @va varchar(max) SELECT @va = dbo.ChoiceToString ('ABALLAND') PRINT @va

La tabella la tabella tbEmpSpec ossia la tabella in cui sono memorizzate le scelte effettuate dall'utente.

8. Uso del try catch in una query sql


ReturnValue bit OUTPUT BEGIN TRY BEGIN TRANSACTION --- QUERY SET @ReturnValue = 0 COMMIT TRANSACTION; END TRY BEGIN CATCH ROLLBACK TRANSACTION; SET @ReturnValue = 1

END CATCH;