Sei sulla pagina 1di 9

Execute Stored Procedure and get return value (int => return)

NOTA:
El return del SP solo retorna un valor entero.







1- Open the connection.
2- create a SqlCommand object, his parameters will be the name of the stored procedure and
de connection.
3- set the type of the command, in this case it will be Stored Procedure.
4- create a return parameter, using the .Parameters.Add("name of the variable that contain the
return value", type of data in this case integer)
5- set this variable how returnValue
6- Execute the command using .ExecuteNonQuery();
7- create a new variable that contain the retunparameter after convert it in string.
8- close the connection.


Execute Stored Procedure and get return value (string=> select
@output)

public string SP_SetMdiagPromote(string SPName, string MdiagName, string UserName, string
Phase, string ECO)
{
SqlParameter ToReturn = new SqlParameter("@ToReturn", SqlDbType.VarChar, 100) {
Direction = ParameterDirection.Output };

SqlConnection connection = new SqlConnection(this.conexion_Project);

SqlCommand command = new SqlCommand("", connection);
connection.Open();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = SPName;
command.Parameters.Add("@MdiagName", SqlDbType.VarChar).Value = MdiagName;
command.Parameters.Add("@UserName", SqlDbType.VarChar).Value = UserName;
command.Parameters.Add("@Phase", SqlDbType.VarChar).Value = Phase;
command.Parameters.Add("@ECO", SqlDbType.VarChar).Value = ECO;
command.Parameters.Add(ToReturn);

command.ExecuteScalar();
string valuetoreturn = ToReturn.Value.ToString();
connection.Close();
return valuetoreturn;
}

Create a alert() into code behind in Asp.net




string script = @"<script language=""JavaScript"">alert('"+GridView1.DataSource.
GetType().ToString()+"');</script>";

ClientScript.RegisterStartupScript(typeof(Page), "Alerta", script);


Boton editar Gridview manualmente

1 - agregar un gridview
2 - Popularlo con el siguiente cdigo:
protected void fillDataGrid()
{
DataTable datos = new DataTable();

datos = DataAccess.readDataTablefromquerystring("select * from
GAFP_App_Setting");

GridView1.DataSource = datos;

GridView1.DataBind();

}

3 - Agregar los databound
<asp:BoundField DataField="Columna" HeaderText="HeaderColumna" />

4 - Agregar en el GridView el siguiente codigo
AutoGenerateColumns="False"

5 - Ir a editar columnas en el GridView y seleccionar los campos que ahora son
Databound como Templates
<Columns>
<asp:TemplateField HeaderText="ID">
<EditItemTemplate>
<asp: TextBox ID="TextBox3" runat="server" Text='<%# Bind("id") %>'
ReadOnly="true"></asp: TextBox >
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("id")
%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="KeySetting">
<EditItemTemplate>
<asp: TextBox ID="TextBox1" runat="server" Text='<%# Bind("KeySetting")
%>'></asp: TextBox >
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("KeySetting")
%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="KeyValue">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("KeyValue")
%>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("KeyValue")
%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="valtest" HeaderText="valtest" />
<asp:CommandField ShowEditButton="True" />

<asp:CommandField ShowDeleteButton="True" />

</Columns>

6 - Agregar como columnas el boton de editar
7 - En el codigo agregar lo siguiente:
protected void GridView1_RowEditing1(object sender, GridViewEditEventArgs e)
{
fillDataGrid();
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

string id =
((TextBox)GridView1.Rows[e.RowIndex].Cells[0].FindControl("TextBox3")).Text;
string KeySetting =
((TextBox)GridView1.Rows[e.RowIndex].Cells[1].FindControl("TextBox1")).Text;
string KeyValue =
((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[1]).Text;


string query = @"update GAFP_App_Setting set KeySetting ='" + KeySetting + "'
,KeyValue='" + KeyValue + "' where id=" + id;


DataAccess.insertfromquerystring(query);

GridView1.EditIndex = -1;
fillDataGrid();
GridView1.DataBind();
}

protected void GridView1_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1; //swicth back to default mode
fillDataGrid();
GridView1.DataBind();
}

8 - Para el botn eliminar agregar el siguiente cdigo:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string id =
((Label)GridView1.Rows[e.RowIndex].Cells[0].FindControl("Label3")).Text;

string query = @"delete from GAFP_App_Setting where id=" + id;


DataAccess.insertfromquerystring(query);
fillDataGrid();
GridView1.DataBind();
}



Seleccionar un tem del DropDownList mediante el texto

Con este cdigo se seleccionara el item que contenga determinado texto.

dropdlKV.SelectedIndex = dropdlKV.Items.IndexOf(dropdlKV.Items.FindByText("texto"));

Llenar un DropDownList mediante un DataTable

DataTable dt = DataAccess.readDataTablefromquerystring("SELECT TypeName FROM mytable");

ddltest.DataSource = dt;
ddltest.DataTextField = "TypeName";
ddltest.DataValueField = "TypeName";
ddltest.DataBind();


Crear Totales en GridView

1) habilitar en el GridView el Footer => ShowFooter="True"

2) Poner el siguiente Codigo:
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
total += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "FileSize"));
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[0].Text = "TOTAL:";
e.Row.Cells[10].Text = total.ToString();
}
}


Alerta antes de eliminar registro GridView

1) habilitar Delete Button => <asp:CommandField ShowDeleteButton="True"/>

<asp:GridView ID="GV_table" runat="server" AutoGenerateColumns="False"
onrowdeleting="GV_table_RowDeleting"

2) Poner el siguiente Codigo:
protected void GV_table_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState == DataControlRowState.Normal) || (e.Row.RowState ==
DataControlRowState.Alternate))
{
LinkButton db = (LinkButton)e.Row.Cells[9].Controls[0];
db.OnClientClick = "return confirm('Are you sure you want to delete this
record?');";
}
}
}
Exportar un GridView a un Excel file

Crear un ImageButton con la imagen de un excelfile y en el evento click agregar el siguiente
codigo:

protected void img_ExcelExport_Click(object sender, ImageClickEventArgs e)
{

if (GridView2.Rows.Count >= 1)
{
string attachment = "attachment; filename=BenchReport.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
this.EnableViewState = false;
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
HtmlForm frm = new HtmlForm();
GridView2.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(GridView2);
frm.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}


}

Archivo de Configuracion

Agregar un nuevo item como Application Configuration File, modificar el XML segun esta
estructura:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ProcessPath" value="E:\xmltoziptest" />
<add key="mtdlpath" value="E:\MTDL" />
<add key="LOB" value="Server,client,notebook"/>

</appSettings>
</configuration>

En el codigo agregar el namespase: using System.Configuration;
y agregar la referencia System.Configuration.
Dentro del codigo para extraer el valor del xml, usar la siguiente instruccion: string path =
ConfigurationManager.AppSettings["ProcessPath"];

Escribir Archivo LOG
Para escribir un archivo log poner el siguiente codigo:
StreamWriter log;

if (!File.Exists("logfile.txt"))
log = new StreamWriter("logfile.txt");
else
log = File.AppendText("logfile.txt");

log.WriteLine("[" + DateTime.Now.ToString() + "] - Error: " + ex.Message);
log.WriteLine();
log.Close();
Comprimir Archivos IONIC library

//================ POR ARCHIVO =========================//

string[] myfiles = Directory.GetFiles(Path);

foreach (string file in myfiles)
{
if (!file.EndsWith(".xml"))
{
continue;
}
myzip.AddFile(file, "");
//el parametro "", agrega solamente el archivo en el .zip y no todo el FULLPATH

}
myzip.Save(zipname) //zipname = nombre del zip, con su fullpath


//================ POR DIRECTORIO =========================//

string[] mydirectories = Directory.GetDirectories(Path)

foreach (string dir in mydirectories)
{
myzip.AddDirectory(dir);
}
myzip.Save(zipname)

//================ LEER CONTENIDO DE UN .ZIP =========================//

using (var zip = ZipFile.Read(zipname))
{
int totalEntries = zip.EntryFileNames.Count;
foreach (string e in zip.EntryFileNames)
{
string name = e; //Nombre del .zip
}
}


//================ DESCOMPRIMIR UN .ZIP =========================//

ZipFile myzip = new ZipFile(@"E:\MTDL\mtdl_fc_client_052813-164352.zip");
//Extract un solo archivo , especificar el path donde se descromprimira
myzip.Extract(@"SigmaProbe_1FMWFX1_2013-05-27_170737.xml",@"E:\MTDL");
//Descomprime todo el .zip en un path especifico
myzip.ExtractAll(@"E:\MTDL\Extract");

Potrebbero piacerti anche