Una clase para simular (en parte) el objeto My de Visual Basic 2005
// Una clase para simular (en parte) el objeto My de Visual Basic 2005 static class My { public static Properties.Settings Settings { get { return Properties.Settings.Default; } } }
xml es XmlDocument
foreach(XmlNode n in xml.ChildNodes) { if (n.NodeType == XmlNodeType.XmlDeclaration) n.ParentNode.RemoveChild(n); }
Con este ejemplo se puede hacer una invocación a funciones que estén en otro fichero utilizando Ajax. En este ejemplo se asocia al evento onBlur de un campo de texto la llamada Ajax dentro de un javascript.
De esta forma el código que esta en cliente abre un canal al servidor y ejecuta el código que haya en el y lo devuelve
//Este es el código que va en cliente <html> <head> <title>Prueba tarifas AJAX</title> </head> <body> CampoTexto<input type="text" id="texto" onblur="calcula()" value="2007"><br/> </html>
<script> //Este es el código que va en cliente function calcula() { // Obtener la instancia del objeto XMLHttpRequest if (window.XMLHttpRequest) { // Mozilla, Safari, ... http_request = new XMLHttpRequest(); } else if (window.ActiveXObject) { // Internet Explorer http_request = new ActiveXObject("Microsoft.XMLHTTP"); } // Preparar la funcion de respuesta http_request.onreadystatechange = muestraContenido; ////////////////////////////////////////////////////////////////////// // Realizar peticion HTTP///////////////////////////////////////////// var url = '/public/api/utilTarifas.aspx?cod='+document.getElementById('texto').value; ////////////////////////////////////////////////////////////////////// http_request.open('GET', url, true); http_request.send(null); function muestraContenido() { if(http_request.readyState == 4) { if (http_request.status == 200) { var documento=http_request.responseText; ////////////////////////////////////////////////////////////////////// // TRATAMOS LA RESPUESTA///////////////////////////////////////////// if (documento !='Error') { alert(documento ); } ////////////////////////////////////////////////////////////////////// } } } } </script>
//Este puede ser el codigo invocado en otra página, en este caso con extensión aspx y que va en el servidor
<%@ Page Language="c#"%> <%@ import Namespace="System.Data" %> <%@ import Namespace="System.Data.OleDb"%> <%@ import Namespace="System.Web" %> <%@ import Namespace="System" %> <%@ import Namespace="System.Net" %> <% try{ String codigo= Request.QueryString["cod"]; String tarifas=""; if(codigo='2007') tarifas="1,2,3,4,5"; else tarifas="6,7,8,9,10"; //Ejecutas tu consulta de BBDD y la devuelves en el string //Este ejemplo sencillo devuelve una serie de valores Response.Write(tarifas); } catch(Exception e) { //Response.Write(e); Response.Write("Error"); } %>
En Vb.net
Private Sub WriteFile(ByVal FileName As String, ByVal data As String) If File.Exists(FileName) Then File.Delete(FileName) Dim swFile As StreamWriter = File.CreateText(FileName) swFile.Write(data) swFile.Flush() swFile.Close() End Sub Private Function ReadFile(ByVal FileName As String) As String Dim ret As String = "" If File.Exists(FileName) Then Dim TheFile As System.IO.StreamReader = New StreamReader(FileName, System.Text.Encoding.Default) ret = TheFile.ReadToEnd() TheFile.Close() End If Return ret End Function
En c#
private void WriteFile(String FileName , String data ){ if (File.Exists(FileName)) {File.Delete(FileName);} StreamWriter swFile = File.CreateText(FileName); swFile.Write(data); swFile.Flush(); swFile.Close(); } private String ReadFile(String FileName ) { String ret = ""; if (File.Exists(FileName)){ System.IO.StreamReader TheFile = new System.IO.StreamReader(FileName, System.Text.Encoding.Default); ret = TheFile.ReadToEnd(); TheFile.Close(); } return ret; }
using System; using System.Threading; namespace CSharpSchool { class Test { static void Main() { Thread firstThread = new Thread(new ThreadStart(fun1)); Thread fsecondThread = new Thread(new ThreadStart(fun2)); firstThread.Start(); secondThread.Start(); console.WriteLine("End of Main()"); } public static void Fun1() { for (int i=1; i<=5; i++) { Console.WriteLine("Fun1() writes: {0}", i); } } public static void Fun2() { for (int i=1; i<=6; i++) { Console.WriteLine("Fun2() writes: {0}", i); } } } }
valor_logico = ((int)clave.GetValue (nombreCadena)) == 1;Para leer los datos del registro. Suponiendo que clave es un RegistryKey ya abierto. Y:
clave.SetValue (nombreCadena, valor_logico ? 1 : 0, RegistryValueKind.DWord);para escribirlo.
public class GestionVentana { Progreso progreso; InvConf.Configuracion conf; public GestionVentana (ref InvConf.Configuracion conf, ref Progreso progreso) { this.conf = conf; this.progreso = progreso; } public void bw_RunWorkerCompleted (object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) { this.progreso.Hide (); } public void bw_DoWork (object sender, System.ComponentModel.DoWorkEventArgs e) { // Esta es la función que tarda varios minutos this.conf.procesarEquipo (); } }Y después en el método principal debemos insertar algo como esto:
System.ComponentModel.BackgroundWorker bw = new System.ComponentModel.BackgroundWorker (); GestionVentana gv = new GestionVentana (ref conf, ref progreso); bw.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler (gv.bw_RunWorkerCompleted); bw.DoWork += new System.ComponentModel.DoWorkEventHandler (gv.bw_DoWork); bw.RunWorkerAsync (); while (bw.IsBusy) { // O cualquier otra actualización en la interfaz que queramos realizar. Application.DoEvents (); }
public static void ShowMessage(System.Web.UI.Page p, string message) { message = message.Replace("'", @"\'"); message = message.Replace("\"", @"\" + '"'); //MessageBox Script String scriptString = "<script language=JavaScript>"; scriptString += "alert('" + message + "');"; scriptString += "</script>"; p.RegisterStartupScript("ShowMessage", scriptString); }
/// <summary> /// Obtiene el valor de un atributo que se encuentra en el Request de la pagina. /// Si no se encuentra el atributo regresa una cadena vacia. /// </summary> /// <param name="Request">Objeto Request de la pagina.</param> /// <param name="attributeName">Nombre del atributo del cual se desea obtener su valor.</param> /// <returns>Regresa el valor del atributo, en caso de no existir retorna una cadena vacia.</returns> public static string getAttribute(System.Web.HttpRequest Request, string attributeName) { string attributeValue=""; try { attributeValue = Request.QueryString[attributeName]; if(attributeValue==null || attributeValue.Trim().Equals("")==true) attributeValue = ""; } catch{} return attributeValue; }
Exportar a Excel
public static void DT2xls(System.Web.HttpResponse Response, DataTable dt) { // exportar a xls Response.Clear(); Response.Buffer= true; Response.AddHeader("Content-Disposition", "attachment; filename=Export.xls"); Response.ContentType = "application/vnd.ms-excel"; System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid(); dg.DataSource = dt; dg.DataBind(); dg.RenderControl(oHtmlTextWriter); Response.Write(oStringWriter); Response.End(); }
Para consola
Public Sub htmlExport() Dim gvEx As New System.Web.UI.WebControls.GridView gvEx.AutoGenerateColumns = True gvEx.AllowSorting = False gvEx.AllowPaging = False Dim stringWrite As New System.IO.StringWriter Dim htmlWrite As New System.Web.UI.HtmlTextWriter(stringWrite) gvEx.DataSource = Me.DataSource gvEx.DataBind() gvEx.RenderControl(htmlWrite) WriteFile(Me.FileName, stringWrite.ToString()) End Sub
Usando excel
Public Sub ExcelExport() Dim oexcel As Excel.Application Try If File.Exists(FileName) Then File.Delete(FileName) 'create new excel application oexcel = CreateObject("Excel.Application") oexcel.Application.DisplayAlerts = True 'add a new workbook 'obook = oexcel.Workbooks.Open(FileName) Dim obook As Excel.Workbook = oexcel.Workbooks.Add() Dim ws As Excel.Worksheet = obook.Sheets(1) ' Add each row of data to the sheet. ' The sheet cell row is incremented by one because the first row was used for the header. For rowIndex As Integer = 1 To DataSource.Rows.Count For colIndex As Integer = 1 To DataSource.Columns.Count TryCast(ws.Cells(rowIndex + 1, colIndex), Excel.Range).Value2 = DataSource.Rows(rowIndex - 1)(colIndex - 1).ToString() Next Next ' Create the headers on the sheet. For colIndex As Integer = 1 To DataSource.Columns.Count TryCast(ws.Cells(1, colIndex), Excel.Range).Value2 = DataSource.Columns(colIndex - 1).ColumnName TryCast(ws.Cells(1, colIndex), Excel.Range).Font.Bold = True TryCast(ws.Cells(1, colIndex), Excel.Range).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter TryCast(ws.Cells(1, colIndex), Excel.Range).EntireColumn.AutoFit() Next oexcel.Visible = False If Password <> "" Then obook.SaveAs(FileName, Excel.XlFileFormat.xlWorkbookNormal, Password, Nothing, False, False, Excel.XlSaveAsAccessMode.xlExclusive, False, False, Nothing, Nothing) Else obook.SaveAs(FileName) End If 'end application object and session obook.Close() obook = Nothing oexcel.Quit() oexcel = Nothing Catch ex As Exception Throw New System.Exception(ex.Message) Finally End Try End Sub