Noticias Weblogs Foros Wiki Código

RecorteX

» CSharp
458 usuarios y 235 recortes de código
Usuario

Contraseña
Crear cuenta
Estás viendo los recortes de la etiqueta CSharp

RSS
Recortes: 18

Etiquetas relacionadas:
vbnet
xml
sql
Explorer
net
threading
hilos
registro
Ajax
Javascript
service
c
web
js
splash
charp
win32
multithreading

Web Reference dinamico C# VS2010

Me topé con el problema siguiente.

Yo hice un producto (web service) que dependia de un web service previamente instalado (Creado por otro desarrollador en otro momento) que es prerequisito de mi webservice.

El chiste es que lo habia tomado de un url, pero cuando cambió al reconfigurar el web.config no tomo el cambio ya que se habia quedado hardcoded.

aparte de hacer lo de la siguiente solucion:
http://www.codeproject.com/Articles/12317/How-to-make-your-Web-Reference-proxy-URL-dynamic
lo que hice fue agregarle este codigo en Resources.cs (Codigo autogenerado).

WEB.CONFIG

 
<?xml version="1.0"?>
<configuration>
  ...
  <appSettings>
    ...
    <add key="LLAVE" value="http://servidor/carpeta/webservice.dll/soap/IProceso"/>
    ...
  </appSettings>
</configuration>
 

REFERENCE.CS

 
 
        protected static string GetApplicationSettings(string sKey)
        {
            string sValue = null;
            //check if the AppSettings section has items
            if (System.Web.Configuration.WebConfigurationManager.AppSettings.Count > 0)
            {
                sValue = System.Web.Configuration.WebConfigurationManager.AppSettings[sKey];
            }
            return sValue;
        }
 
        /// <remarks/>
        public IProcesosWSservice() {
            string TressProcesos = GetApplicationSettings("LLAVE");
            this.Url = TressProcesos;
            if ((this.IsLocalFileSystemWebService(this.Url) == true)) {
                this.UseDefaultCredentials = true;
                this.useDefaultCredentialsSetExplicitly = false;
            }
            else {
                this.useDefaultCredentialsSetExplicitly = true;
            }
        }
 

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

 
// 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;
        }
    }
}
 

Remover declaracion de xml

xml es XmlDocument

 
foreach(XmlNode n in xml.ChildNodes)
{ 
    if (n.NodeType == XmlNodeType.XmlDeclaration)
       n.ParentNode.RemoveChild(n);
}
 

Ejemplo sencillo Ajax - Invocación y recogida de datos

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");
}
%>
 

Traer un DT desde un query en SqlServer

 
    Private Function getDT(ByVal qry As String, ByVal connectionString as string) As DataTable
        Dim dataSet As DataSet = New DataSet
        Dim conn As New SqlConnection(connectionString)
        Dim cmdString As String = qry
        Dim dataAdapter As New SqlDataAdapter(cmdString, conn)
        Dim ds As New DataSet()
        dataAdapter.Fill(ds, "dt")
 
        Return ds.Tables("dt")
    End Function
 
 
    private DataTable getDT(String qry, String  connectionString)
    {
        DataSet dataSet = new DataSet();
        SqlConnection conn = new SqlConnection(connectionString);
        SqlDataAdapter dataAdapter = new SqlDataAdapter(qry, conn);
        DataSet ds= new DataSet();
        dataAdapter.Fill(ds, "dt");
  
        return ds.Tables ["dt"];
    }
 

Leer y escribir archivos de texto

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;
        }
 

Multithreading en C#

Este es un layout rapido para poder usar multithreading en C#
 
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);
      }
    }
  }
}
 

C#, Registro y booleanos

No se si os habrá pasado alguna vez. Al intentar leer un valor lógico del registro con C# me dice sencillamente, que me busque la vida.
Así que, hago esto que es igual de rápido y así de fácil:

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.

No es muy complicado ¿ verdad ?

Splash con operación larga en inicio

Si al arrancar tu aplicación tienes que hacer una operación que puede tardar varios minutos puede llegar a desesperar al usuario.
Para eso se supone que se inventaron las ventanas de splash. Sin embargo, si en esa ventana de splash quieres poner una imagen animada, una barra de progreso o cualquier otra cosa para demostrar al usuario que no se le ha colgado la aplicación hay que dar un pequeño rodeo. Al menos es la mejor forma que he encontrado. De cualquier otra forma, mostraremos un bonito rectángulo gris que no dará demasiada buena imagen de lo que hemos hecho.

Primero creo una clase que encapsulará el trabajo con la ventana de splash.

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 ();
}

Crear mensaje

Manda un mensaje de alert de js, desde csharp en una webapp
 
		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);			
		}
 
info@recortex.com - Proyecto: Juanjo Navarro, 2006 - Diseño: Albin - Información legal y técnica