Skip to content

Instantly share code, notes, and snippets.

@mariobot
Last active August 29, 2015 14:05
Show Gist options
  • Save mariobot/d095539c9da1a59ab32f to your computer and use it in GitHub Desktop.
Save mariobot/d095539c9da1a59ab32f to your computer and use it in GitHub Desktop.
Chuletas .Net /*Pequeños conceptos y tips para desarrollar en .Net*/
//------------------------------ concatenar en el eval
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "~/styles/images/" + Eval("value") + ".png"%>'
ToolTip='<%# Convert.ToDateTime(Eval("value")).ToString("dddd d, MMMM yyyy -- HH:mm:ss") %>' />
ImageUrl='<%# "~/fixed/showimage.aspx?img=" + Eval("im_image")%>'
ImageUrl='<%# Eval("im_image","~/fixed/showimage.aspx?img={0}")%>'
//----------------------------------- para dormir el proceso
Thread.Sleep(300); //en milisegundos
//----------------------------------- Acceder a la cadena de conexion en el webConfig
string OraString = ConfigurationManager.ConnectionStrings["C"].ConnectionString;
//----------------------------------- Condicional en una sola linea
string = bool ? string.empty : cadena
string = (cadena == string.empty) ? "Valor vacio" : cadena
el ? se puede considerar como el if
el : se puede considerar como el else
//----------------------------------- Para sustraer caracteres a un string
string saludo = "Hola Mundo";
saludo.Replace("Mundo","Infirno");
saludo.Remove(1) // quita el segundo caracter.
//----------------------------------- Subir un archivo
HttpFileCollection archivos = Request.Files;
for (int i = 0; i <= archivos.Count - 1; i++)
{
HttpPostedFile postedFile = archivos[i];
if (postedFile.ContentLength > 0)
{
postedFile.SaveAs(Server.MapPath(@"uploads\") + Path.GetFileName(postedFile.FileName));
lblMsg.Text = "Archivos subidos correctamente.";
}
}
//---------------------------------- Server.Map para saber la ruta de nuestros archivos en asp.net
<%
response.write(Server.MapPath("test.asp") & "<br />")
response.write(Server.MapPath("script/test.asp") & "<br />")
response.write(Server.MapPath("/script/test.asp") & "<br />")
response.write(Server.MapPath("\script") & "<br />")
response.write(Server.MapPath("/") & "<br />")
response.write(Server.MapPath("\") & "<br />")
%>
//---------- cada consulta anterioro imprime lo siguiente
c:\inetpub\wwwroot\script\test.asp
c:\inetpub\wwwroot\script\script\test.asp
c:\inetpub\wwwroot\script\test.asp
c:\inetpub\wwwroot\script
c:\inetpub\wwwroot
c:\inetpub\wwwroot
HttpContext.Current.Server.MapPath("/")
//------------------------ Obtener archivos de un fichero ver System.IO
DirectoryInfo ListaArchivos = new DirectoryInfo(Server.MapPath("/") + rutaImgDocuments );
foreach (FileInfo archivo in ListaArchivos.GetFiles("*")
archivo.name
//------------Definir una lista de strings
List<string> Listadestrings = new List<string();
Listadestrings.Add("primero");
Listadestrings.Add("segundo");
Listadestrings.Add("tercero");
//-------------Para calcular la diferencia entre dos horas.
DateTime startTime = DateTime.Now;
DateTime endTime = DateTime.Now.AddSeconds( 75 );
TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( "Time Difference (seconds): " + span.Seconds );
Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
Console.WriteLine( "Time Difference (hours): " + span.Hours );
Console.WriteLine( "Time Difference (days): " + span.Days );
//-------------para colocar el cursor en modod de espera se utiliza
Cursor.Current = Cursors.WaitCursor;
Cursor.Current = Cursors.Default;
//-------------Para establecer la pagina de inicio predeterminada en ASP.Net
<system.webServer>
<defaultDocument>
<files>
<add value="MyDefaultPage.aspx" />
</files>
</defaultDocument>
</system.webServer>
//------------ Usando la cadena de conexion
string cadenaConexion = @"server=(local)\PRODUCCION; database=BDPolizas; user id=sa; password=password; Trusted_Connection=False; timeout = 60 ";
using (SqlConnection con = new SqlConnection(cadenaConexion))
{
try
{
con.Open();
Console.WriteLine("CONEXION EXITOSA");
}
catch (Exception error)
{
Console.WriteLine(error.Message);
Console.ReadKey();
}
finally {
con.Close();
}
}
DataSet DSCitas = new DataSet();
using (SqlConnection conn = new SqlConnection(ConnStringDataBase))
{
try
{
string sqltext = "SELECT * FROM CITAS";
SqlDataAdapter dAdapter = new SqlDataAdapter(sqltext, conn);
dAdapter.Fill(DSCitas);
return DSCitas;
// -------------- Utilizando Parametros en URL
response.redirect("a.aspx?ids=1&val=100",true)
a=Request.QueryString("ids")
b= Request.QueryString("val")
a = 1
b = 100
//----------------- CONSULTA ORACLE
string connStr = ConfigurationManager .ConnectionStrings["connString"].ConnectionString;
OracleConnection OraCon = null ;
OracleCommand OraComm = null ;
OracleDataAdapter OraDataAdapter = null ;
DataSet data = null;
public DataSet GetStoreInfo()
{
using (OraCon = new OracleConnection(connStr))
{
using (OraComm = new OracleCommand( "MY.PROCEDURE" , OraCon))
{
data = new DataSet ();
try
{
OraCon.Open();
OraComm.CommandType = CommandType .StoredProcedure;
OraComm.Parameters.Add( "OUTCURSOR" , OracleDbType .RefCursor).Direction = ParameterDirection .Output;
OraDataAdapter = new OracleDataAdapter (OraComm);
OraDataAdapter.TableMappings.Add( "INFO" , "OUTCURSOR" );
OraDataAdapter.Fill(data);
}
catch (OracleException errorOra)
{
throw new Exception( "Oracle error - " + errorOra.Message + errorOra.ToString(), errorOra.InnerException);
}
catch (Exception erroSys)
{
throw new Exception( "Oracle error - " + erroSys.Message + erroSys.ToString(), erroSys.InnerException);
}
}
}
return data;
}
//------------- Retornar la sesion en una clase statica
System.Web.SessionState.HttpSessionState sessions = HttpContext.Current.Session;
String _mySession = sessions[ Constants.NameSessionUser];
//-------------- Para verificar que un archivo existe en asp.net
archivo = file.txt example
if (File .Exists(Server.MapPath("~/"+ archivo)))
using ( StreamReader reader = new StreamReader(Server.MapPath("~/" + archivo)))
while (reader.Peek() >= 0)
HTML += reader.ReadLine();
//----------------- Export DataTable to excel.
public static void ExportDataTableToExcel( string fileName, DataTable _datatable)
{
String style = @"<style> .textmode { mso-number-format:\@; } </script> ";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string .Format("attachment; filename={0}" , fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel" ;
using ( StringWriter sw = new StringWriter ())
{
using ( HtmlTextWriter htw = new HtmlTextWriter (sw))
{
// Create a form to contain the grid
Table table = new Table();
for ( int i = 0; i < _datatable.Rows.Count; i++)
{
TableRow row = new TableRow();
for ( int j = 0; j < _datatable.Columns.Count; j++)
{
TableCell cell = new TableCell();
cell.Text = _datatable.Rows[i][j].ToString();
row.Cells.Add(cell);
}
// Add the TableRow to the Table
table.Rows.Add(row);
}
table.RenderControl(htw);
/// Type text
HttpContext.Current.Response.Write(style);
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
//------- Cargar un archivo XML en una lista o entidad.
customerList = (
from e in XDocument.Load( "MyFile.xml").
Root.Elements( "customer")
select new Customer
{
CustomerID = ( string)e.Element( "id"),
CompanyName = ( string)e.Element( "name"),
Address = ( string)e.Element( "address"),
City = ( string)e.Element( "city"),
Region = ( string)e.Element( "region"),
PostalCode = ( string)e.Element( "postalcode"),
Country = ( string)e.Element( "country"),
Phone = ( string)e.Element( "phone"),
Fax = ( string)e.Element( "fax"),
Orders = (
from o in e.Elements( "orders").Elements("order" )
select new Order
{
OrderID = ( int)o.Element( "id"),
OrderDate = ( DateTime)o.Element( "orderdate"),
Total = ( decimal)o.Element( "total")
})
.ToArray()
})
.ToList();
//--------------Exportat DataTable to excel in WPF
try
{
Microsoft.Office.Interop.Excel. Application excel = null ;
Microsoft.Office.Interop.Excel. Workbook wb = null;
object missing = Type.Missing;
Microsoft.Office.Interop.Excel. Worksheet ws = null;
Microsoft.Office.Interop.Excel. Range rng = null;
try
{
excel = new Microsoft.Office.Interop.Excel. Application();
wb = excel.Workbooks.Add();
ws = (Microsoft.Office.Interop.Excel. Worksheet)wb.ActiveSheet;
for ( int Idx = 0; Idx < dataToExcel.Columns.Count; Idx++)
{
ws.Range[ "A1"].Offset[0, Idx].Value = dataToExcel.Columns[Idx].ColumnName;
}
for ( int Idx = 0; Idx < dataToExcel.Rows.Count; Idx++)
{
ws.Range[ "A2"].Offset[Idx].Resize[1, dataToExcel.Columns.Count].Value =
dataToExcel.Rows[Idx].ItemArray;
}
excel.Visible = true;
wb.Activate();
}
catch ( COMException ex)
{
MessageBox.Show("Error asignando el archivo Excel: " + ex.ToString());
}
}
catch ( Exception ex)
{
MessageBox.Show("Error: " + ex.ToString());
}
//----PAGINACION Y ORDENACION DE GRIDVIEWS
// PAGINACION Y ORDENACION
SortDirection _sortDir;
protected void gvVentasByRegions_PageIndexChanging( object sender, GridViewPageEventArgs e)
{
pageAndSort(gvVentasByRegions, GridViewSortExpresion, (DataTable)Session[_nameSessionData], e.NewPageIndex);
}
protected void pageAndSort( GridView gv, string sortField, DataTable dt, int iPage)
{
_sortDir = GridViewSortDirection;
Utilities.pageAndSort(gv, ref _sortDir, sortField, dt, iPage);
GridViewSortDirection = _sortDir;
}
protected void gvVentasByRegions_Sorting( object sender, GridViewSortEventArgs e)
{
GridViewSortExpresion = e.SortExpression;
pageAndSort(gvVentasByRegions, GridViewSortExpresion, (DataTable)Session[_nameSessionData], gvVentasByRegions.PageIndex);
}
/// <summary>
/// Manejo de las direcciones de ordenacion en la grilla
/// </summary>
public SortDirection GridViewSortDirection
{
get
{
if (ViewState[ "sortDirection"] == null )
ViewState[ "sortDirection"] = SortDirection .Ascending;
return ( SortDirection)ViewState["sortDirection" ];
}
set { ViewState[ "sortDirection"] = value ; }
}
/// <summary>
/// Manejo de los campos de ordenacion o exp. de ordenacion
/// </summary>
public string GridViewSortExpresion
{
get
{
if (ViewState[ "sortExpresion"] == null )
ViewState[ "sortExpresion"] = string .Empty;
return ( string)ViewState[ "sortExpresion"];
}
set { ViewState[ "sortExpresion"] = value ; }
}
//----------- Default button para un control
<asp:Panel runat="server" DefaultButton="Button1">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" style="display:none" OnClick="Button1_Click" /></asp:Panel>
//----- Registrar codigo jquery o javascript desde el codebehind
string script = "alert(' " + "Hola desde el code behind " + " ');" ;
ScriptManager.RegisterStartupScript(updatePanel, Page.GetType(), "msg" , script, true );
//Tener en cuenta registrar el id del updatepanel
//--------------redirect page 404 en el redirect at web.config
<customErrors mode="RemoteOnly"
defaultRedirect="~/error404.aspx">
<error statusCode="404" redirect="~/error404.aspx"/>
</customErrors>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment