lunes, 22 de agosto de 2011

HowTo: Crear una pantalla de inicio (splash screen)

Nota: Otro post en respuesta a una pregunta bastante habitual en los foros MSDN: ¿Cómo crear una pantalla de inicio para mi aplicación?

He creado un pequeño proyecto de ejemplo, que pueda servir como plantilla base para que cada uno se lo personalice para su aplicación. Este proyecto tiene lo básico: Un formulario sin bordes con una imagen, una barra de progreso, una etiqueta para el título, otra para ir mostrando mensajes, y un botón por si se desea cancelar la carga del programa (al estilo Office 2010).

SplashScreen

Él proyecto es muy sencillo y lo podéis descargar desde aquí:

La pantalla de inicio utiliza un thread para mostrar los diferentes mensajes al cargar, ya que así no se bloquea la aplicación (y la barra de progreso). Esto es así porque en el proyecto de ejemplo, al cargar la pantalla de inicio se lanza un segundo hilo que llama a un método ‘initApplication’, y desde éste método simulamos varios procesos largos (en realidad de un segundo cada uno), y cada vez que se inicia uno de ellos hay que cambiar el mensaje:

public void initApplication()


{


    Thread.Sleep(DEFAULT_TIME);


    this.Invoke((MethodInvoker)(() => setMessage("Searching for updates...")));


    Thread.Sleep(DEFAULT_TIME);


    this.Invoke((MethodInvoker)(() => setMessage("Connectiong to database...")));


    Thread.Sleep(DEFAULT_TIME);


    this.Invoke((MethodInvoker)(() => setMessage("Connectiong to webservices...")));


    Thread.Sleep(DEFAULT_TIME);


    this.Invoke((MethodInvoker)(() => setMessage("Loading settings...")));


    Thread.Sleep(DEFAULT_TIME);


    this.Invoke((MethodInvoker)(() => setMessage("Loading user preferences...")));


    Thread.Sleep(DEFAULT_TIME);


    this.Invoke((MethodInvoker)(() => setMessage("Starting application...")));


    Thread.Sleep(DEFAULT_TIME);


    if (this.InvokeRequired) this.Invoke(new Action(finishProcess));


}


Recordar que desde un hilo que no sea el hilo principal, en .NET no se puede actualizar la interfaz de usuario directamente. En su lugar debemos usar el método Invoke. En el ejemplo anterior llamamos a un método ‘setMessage’ que se encarga de mostrar el texto en la etiqueta correspondiente. Para poder llamar a este método mediante Invoke tenemos dos opciones: Podemos usar un MethodInvoker o un Action, en nuestro caso usaremos el primero, ya que un Action se usa cuando no hay paso de parámetros, y este método precisa de un parámetro con el mensaje a mostrar:



public void setMessage(string msg)


{


    messageLabel.Text = msg;


}


Una vez finalizado el proceso de carga, se cierra el formulario y se devuelve un DialogResult = Ok. Por otro lado si en cualquier momento de la carga el usuario ha pulsado el botón ‘close’, se hace lo mismo pero devolviendo un DialogResult = Cancel:



private void finishProcess()


{


    this.DialogResult = System.Windows.Forms.DialogResult.OK;


    this.Close();


}


void closeButton_Click(object sender, EventArgs e)


{


    this.DialogResult = System.Windows.Forms.DialogResult.Cancel;


    this.Close();


}


Como veis el proyecto es muy sencillo, sólo debéis recordar un detalle importante: En una aplicación WinForms el punto de entrada a la misma se define en el método estático Main del Program.cs, y aquí hay una línea que inicializa el formulario inicial de nuestra aplicación:



Application.Run(new fMain());


Lo primero que solemos pensar es que aquí deberíamos lanzar el formulario fSplashScreen, y al cerrarlo mostrar el formulario principal, verdad? Pues no, no podemos hacer eso. El motivo no es otro que este formulario inicial va a definir el ciclo de vida de nuestra aplicación, y si lo cerramos, cerramos la aplicación. Ya se que en VB puede cambiarse este comportamiento, pero entre nosotros... hacerlo siempre me ha parecido una chapuza :-)



Así pues, aquí lanzaremos el formulario principal, y éste, al cargarse (mientras todavía no es visible) lanzará la pantalla de inicio de forma modal y esperará el valor de retorno. Si al cerrarse la pantalla de bienvenida el valor de retorno es Ok, continúa la carga y muestra el formulario principal, en caso contrario cierra el formulario principal y con por ende la aplicación:



void fMain_Load(object sender, EventArgs e)


{


    showSplashScreen();


}


 


private void showSplashScreen()


{


    using (fSplashScreen fsplash = new fSplashScreen())


    {


        if (fsplash.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) this.Close();


    }


}


 



 



link http://geeks.ms/blogs/lfranco/archive/2010/11/26/howto-crear-una-pantalla-de-inicio-splash-screen.aspx

miércoles, 3 de agosto de 2011

Create Simple Web Service in Visual Studio 2008 / 2010

 

 

This tutorial explains how we can create simple Web Services using Visual Studio 2008 or Visual Studio 2010.

If you are interested in creating web services in java, please follow my post
Create Web Service in Java Using Apache Axis2 and Eclipse

1. Create the Web Service


First create new project and select "New ASP.NET Web Service Application" and I'm giving the name "MyFirstWebService" to it, you can give any name to your project.

Now you can see auto generated code that you can add methods to create your web service. You can see simple method "HelloWorld" and in this sample code I have removed it.
I'm going to add simple method called "simpleMethod" which takes a string as an input and add "Hello" to beginning of that string. Now the code will appear like bellow.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
 
namespace MyFirstWebService
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string simpleMethod(String srt)
        {
            return "Hello "+srt;
        }
 
        [WebMethod]
        public int anotherSimpleMethod(int firstNum, int secondNum)
        {
            return firstNum + secondNum;
        }
 
    }
}

Then you can run your code and you can see the resulting page as bellow.

2. Create the Client Program

We have created our simple web service and we have to create small client program to use this web service. There you can open another instant of Visual Studio and create new "Console Application" project.

Then you have to add Service Reference so that you can access your web service. Here are the screen-shots.

Here you have to give the URL of the web service we created earlier.
As I said before previously created web service application should be running on another instant of Visual Studio.

Note that I have set the "Web reference name" as "TestWeb".

 

Now you can update your client program using following code. Note the line 5 "using WebServiceTest.TestWeb;".

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebServiceTest.TestWeb;
 
namespace WebServiceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Service1 webservice = new Service1();
            string srt = webservice.simpleMethod("Saranga Rathnayake");
            Console.WriteLine(srt);
            Console.WriteLine(webservice .anotherSimpleMethod(4,3));
        }
    }
}

 

Now you can run the client program to see the result.

3. Publish Our Web Service in Internet Information Service (IIS)

Let's see how we can publish our web service in IIS. There first stop the web service application and go to the Solution Explore and Right Click on the project. Then select "Publish...".

Then the following window will appear and there you can directly publish to the IIS by selecting "Web Deploy" as the publishing method. But here I'm going to use the "File System as the publishing method. There you have to provide the target location. I have created new folder called "MyApp" in my D drive and selected it.

Now click "Publish" and check the "MyApp" folder. There you will be able to see Service1.asmx file, Web.config file and bin folder which contains the DLL file has been generated.
Now enable IIS in your computer and open IIS Manager. I'm going to add my service to Default Web Site. There Right Click on the "Default Web Site" and click "Add Application...".

 

There you will get following window. Now you can provide appropriate Alias (I have given testservice) and select the physical path of your application. There you can provide the path to the folder we created previously as following figure and click Ok.

You have to make sure that the application pool identity has Read access to the physical path. So it is better if you copy your files to the "wwwroot" folder other than keep it in separate partition. Please check the following screen-shot

Now restart the IIS and goto http://localhost/testservice/Service1.asmx. You will be able to see the Web Service running.

Now you have published your web service in IIS and you can update the Client Program by giving the new Web Reference URL using Properties Window.

 

link http://sarangasl.blogspot.com/2010/09/create-simple-web-service-in-visual.html

ImageList.Images Property

 

Gets the ImageList.ImageCollection for this image list.

Namespace: System.Windows.Forms
Assembly: System.Windows.Forms (in System.Windows.Forms.dll)

Type: System.Windows.Forms.ImageList.ImageCollection

The collection of images.

Remarks


If the image collection has not yet been created, it is created when you retrieve this property.

 

Examples


The following code example demonstrates constructing an ImageList, adding images to the Images property, setting the ImageSize property, and using the Draw method. To run this example, place it in a form containing a button named Button1. The example assumes the existence of FeatherTexture.bmp and Gone Fishing.bmp at c:\Windows\. Change the example accordingly if the bitmaps do not exist on your system, or exist at another location.

 

internal System.Windows.Forms.ImageList ImageList1;

// Create an ImageList Object, populate it, and display
// the images it contains.
private void Button1_Click(System.Object sender,
System.EventArgs e)
{

// Construct the ImageList.
ImageList1 = new ImageList();

// Set the ImageSize property to a larger size
// (the default is 16 x 16).
ImageList1.ImageSize = new Size(112, 112);

// Add two images to the list.
ImageList1.Images.Add(
Image.FromFile("c:\\windows\\FeatherTexture.bmp"));
ImageList1.Images.Add(
Image.FromFile("C:\\windows\\Gone Fishing.bmp"));

// Get a Graphics object from the form's handle.
Graphics theGraphics = Graphics.FromHwnd(this.Handle);

// Loop through the images in the list, drawing each image.
for(int count = 0; count < ImageList1.Images.Count; count++)
{
ImageList1.Draw(theGraphics, new Point(85, 85), count);

// Call Application.DoEvents to force a repaint of the form.
Application.DoEvents();

// Call the Sleep method to allow the user to see the image.
System.Threading.Thread.Sleep(1000);
}
}

 

setting the ImageSize property and the use of the Draw method.  

To run this sample place it in a form containing a button named Button1.
The sample assumes the existence of FeatherTexture.bmp and
Gone Fishing.bmp at c:\Windows\. Change the sample accordingly if the
 
link http://msdn.microsoft.com/en-us/library/system.windows.forms.imagelist.images.aspx

C# TreeView Node Expand / Collapse Events

 

 

Ejemplo



TreeNode node = null;


And in your expand event, assign the expanded node to the variable:



private void treeView1_AfterExpand(object sender, TreeViewEventArgs e)
{
node = e.Node;
}


And when a node is collapsed make it null:



private void treeView1_AfterCollapse(object sender, TreeViewEventArgs e)
{
node = null;
}


And after loading data to the view do the following check:



if (node != null)
{
foreach (TreeNode n in treeView1.Nodes)
{
if (n.Text == node.Text)
{
n.Expand();
break;
}
}

}

Primer Proyecto en Azure Visual Studio 2010- Windows Azure Training Series – Creating Your First Azure Project

 

This is another in a series of articles on getting started with Windows Azure.  This post will walk you through creating a Windows Azure application. It assumes that you have Visual Web Developer 2010 Express already installed (or Visual Studio 2010), along with the Azure Tools for Visual Studio. If you don’t, see my previous post Windows Azure Training Series – Setting up a Development Environment for Free.

You’ll create a simple ASP.NET application that just squares a number.

 

Creating a Windows Azure Project in Visual Studio

Start Visual Web Developer 2010 Express (or Visual Studio), and then select the File | New Project menu. The New Project dialog will open. ExpandVisual C#, in the Installed Templates tree view, and then click on the Cloudbranch. From the list of templates on the right, select Windows Azure Project.

Visual Basic would work just as well, but the code later on is in C#.

Give your project the name “SquareANumberAzureProject”. Also, set a location where you want to save the project. Then, click the OK button. See the screen shot below.

The New Windows Azure Project dialog will open. Select ASP.NET Web Rolefrom the list on the left, and click on the right arrow to move it to the list on the right. Hover over the Web Role and a pencil icon will appear. Click on that icon, then change the name of the role to “SquareANumber.Web”. When done, clickOK. See the screenshot below.

Nombre.Web es importante

Editing an Azure Web Role in Visual Studio

Your Windows Azure project will be created, and will open in Visual Studio. You should see the Solution Explorer window on the right.

Two projects were created, an ASP.NET Web project and an Azure service project. The Azure Web application is edited the same way as any other ASP.NET application. The Azure service project is used to configure the application, and to create a deployment package when you are ready to upload the application to the cloud (we’ll cover that in a later post).

Let’s make the application do something. In Solution Explorer, double-click on the file Default.aspx to open it in the code editor. At the bottom of the code editor, click the Design button to see the graphical editor. Delete the existing content, and then drag a TextBox, Button and Label onto the Web page from the toolbox. The page should look similar to the screenshot below.

You need to write some code to take the number entered in the text box, square it, and put the answer in the label. Double-click on the button, and an event handler will be created. The code below will work well enough for this program.

Running your Azure Project using the Windows Azure Platform Emulator

From the Visual Web Developer toolbar, click the green run button, or select the Debug | Start Debugging menu. You’ll likely get the error shown below.

Save your work and then close Visual Web Developer. To run Visual Web Developer with elevated privileges, right-click on its icon in the Start menu and select Run as administrator. See the screenshot below.

Once Visual Web Developer starts open your project and try to run it again. It will take a little while, but your program should start and you will be able to square some numbers! The reason it takes a little while for the program to start, is because it is running using your development machine’s local Windows Azure Platform Emulator. You should be able to see the emulator’s icon in the Windows taskbar on the lower right side of your screen. It’s the one that looks like a blue Windows logo, as shown below.

Right-click on the Azure emulator’s icon, and then select Show Compute Emulator UI. This will open a form that displays the Azure services running on your machine, and their status. See the screen shot below.

Summary

Visual Studio and the Azure tools make creating Windows Azure Web applications easy. The Windows Azure Platform Emulator makes it easy to test Azure applications on your local development machine. In a later post, I’ll cover deploying this application to the cloud.

To learn more about Windows Azure, come to Learning Tree course 2602, Windows Azure Platform Introduction: Programming Cloud-Based Applications.

 

link http://cloud-computing.learningtree.com/2011/01/21/getting-started-with-windows-azure-%E2%80%93-creating-your-first-azure-project/

(drag and drop) Cómo agregar funcionalidad de arrastrar y colocar TreeView en una aplicación de Visual C#

En este artículo paso a paso se describe cómo realizar una operación de arrastrar y colocar con nodos de árbol entre dos controlesTreeView en una aplicación de Visual C#.

Volver al principio

Requisitos
En la lista siguiente se indican el hardware, el software, la infraestructura de red y los Service Pack recomendados que necesitará:
  • Visual C# .NET o Visual C# 2005
En este artículo se da por supuesto que está familiarizado con los temas siguientes:
  • Control TreeView de Windows Forms
  • Control de eventos de Windows Forms

Volver al principio

Descripción de la técnica
El control TreeView ofrece tres eventos de arrastrar y colocar que debe controlar:
  • ItemDrag: Este evento se genera desde el control TreeView de origen en cuanto el usuario empieza a arrastrar el nodo de árbol. Cuando esto ocurra, llame al método DoDragDrop para iniciar el procedimiento de arrastrar y colocar.
  • DragEnter: después de iniciar la operación de arrastrar y colocar, debe controlar el evento DragEnter del control TreeView de destino. Este evento se produce cuando el usuario arrastra el objeto TreeNode desde el control TreeView de origen hasta un punto dentro de los límites del control TreeView de destino. El evento DragEnter permite que el control TreeView de destino especifique si la operación de arrastre es válida para este control. El código de ejemplo de este artículo sólo permite la operación de desplazamiento.
  • DragDrop: el último evento que hay que controlar es el evento DragDrop del control TreeView de destino. Este evento se produce cuando el objeto TreeNode que se arrastra se ha colocado en el control TreeView de destino. Para controlar este evento, recupere el objeto TreeNode y agréguelo al control TreeView de destino. En el código de ejemplo se utiliza el objetoData para recuperar los datos.
El código de ejemplo de este artículo garantiza que se ha arrastrado un objeto TreeNode hasta el control TreeView de destino. El método GetData del objeto Data recupera el nodo que se arrastra desde el control de origen. El método GetNodeAt determina en qué punto del control de destino se coloca este nodo. Una vez que determine la posición, agregue el nodo de origen como secundario del nodo de destino. Puesto que este ejemplo realiza una operación de desplazamiento, el último paso consiste en quitar el nodo de origen del control TreeView original.

Volver al principio

Pasos para crear el ejemplo
  1. Cree una nueva aplicación para Windows en Visual C#. De forma predeterminada, se crea un formulario denominado Form1.
    Nota
    Se debe cambiar el código en Visual Studio 2005. Cuando crea un proyecto de Windows Forms, Visual C# agrega un formulario al proyecto de manera predeterminada y le asigna el nombre Form1. Los dos archivos que representan el formulario se denominan Form1.cs y Form1.designer.cs. Debe escribir el código en Form1.cs; el archivo designer.cs es donde el Diseñador de Windows Forms escribe el código que implementa todas las acciones que realizó arrastrando y colocando controles desde el cuadro de herramientas.
    Para obtener más información acerca del Diseñador de Windows Forms en Visual C# 2005, visite el siguiente sitio Web de Microsoft:

    http://msdn2.microsoft.com/en-us/library/ms173077.aspx

  2. Utilice el cuadro de herramientas para agregar dos controles TreeView a Form1. De forma predeterminada se crean TreeView1y TreeView2.
  3. Para permitir que los controles TreeView se puedan arrastrar y colocar, cambie la propiedad AllowDrop de TreeView1 yTreeView2 a True en la ventana Propiedades.

Haga doble clic en Form1 para generar el controlador de métodos del evento Load de Form1. Agregue el código siguiente para llenar los dos controles TreeView con objetos TreeNode y para definir los controladores de eventos:



private void Form1_Load(object sender, System.EventArgs e)
{
TreeNode ParentNode1;
TreeNode ParentNode2;

ParentNode1 = treeView1.Nodes.Add("tv1");
ParentNode1.Nodes.Add("tv1FirstChild");
ParentNode1.Nodes.Add("tv1SecondChild");
ParentNode1.Nodes.Add("tv1ThirdChild");
ParentNode1.Nodes.Add("tv1FourthChild");
ParentNode1.Expand();

ParentNode2 = treeView2.Nodes.Add("tv2");
ParentNode2.Nodes.Add("tv2FirstChild");
ParentNode2.Nodes.Add("tv2SecondChild");
ParentNode2.Expand();
this.treeView1.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.treeView_ItemDrag);
this.treeView2.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.treeView_ItemDrag);
this.treeView1.DragEnter += new System.Windows.Forms.DragEventHandler(this.treeView_DragEnter);
this.treeView2.DragEnter += new System.Windows.Forms.DragEventHandler(this.treeView_DragEnter);
this.treeView1.DragDrop += new System.Windows.Forms.DragEventHandler(this.treeView_DragDrop);
this.treeView2.DragDrop += new System.Windows.Forms.DragEventHandler(this.treeView_DragDrop);
}



Agregue el controlador de métodos siguiente para controlar el evento ItemDrag de TreeView1 o TreeView2, dependiendo de la dirección de la operación de arrastre. Este código inicia una operación de desplazamiento del elemento que se está arrastrando.








private void treeView_DragEnter(object sender,
System.Windows.Forms.DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}



Agregue el controlador de métodos siguiente para controlar el evento DragEnter de TreeView1 o TreeView2, dependiendo de la dirección de la operación de arrastre:








private void treeView_DragEnter(object sender,
System.Windows.Forms.DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}



Agregue el método siguiente a la clase Form1 de forma que siga inmediatamente al método que agregó en el paso anterior:








private void treeView_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
TreeNode NewNode;

if(e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))
{
Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
TreeNode DestinationNode = ((TreeView)sender).GetNodeAt(pt);
NewNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");
if(DestinationNode.TreeView != NewNode.TreeView)
{
DestinationNode.Nodes.Add((TreeNode) NewNode.Clone());
DestinationNode.Expand();
//Remove Original Node
NewNode.Remove();
}
}
}




  1. Genere y ejecute el proyecto. Arrastre nodos desde un control TreeView hasta el otro. Observe que se quita el nodo del control de origen y se agrega como nodo secundario al control de destino.



Volver al principio



Notas

El ejemplo que se ofrece en este artículo está pensado con fines demostrativos únicamente. Por tanto, solo ilustra cómo utilizar el controlTreeView en un escenario simplificado. Para reducir el tamaño del ejemplo, no se tienen en cuenta varios escenarios. Por ejemplo, el código no le permite realizar una operación de arrastrar y colocar con nodos del mismo control TreeView.


El código tampoco trata el escenario en el que un usuario no coloca el objeto en un nodo concreto del control TreeView de destino. Para controlar este escenario, compruebe si DestinationNode es nulo; si lo es, puede agregar el objeto que se está arrastrando hasta la raíz del control TreeView y así sucesivamente.

 



link http://support.microsoft.com/kb/307968

CloudBlobClient.ListContainers Method () Listar todos los contenedores Azure

 

Windows Azure Platform

Returns an enumerable collection of containers.

Namespace: Microsoft.WindowsAzure.StorageClient
Assembly: Microsoft.WindowsAzure.StorageClient (in microsoft.windowsazure.storageclient.dll)

 

Ejemplo



static void ListContainersInAccount(Uri blobEndpoint, string accountName, string accountKey)
{
//Create service client for credentialed access to the Blob service.
CloudBlobClient blobClient = new CloudBlobClient(blobEndpoint, new StorageCredentialsAccountAndKey(accountName, accountKey));

//List all containers in this storage account.
foreach (var container in blobClient.ListContainers())
{
Console.WriteLine("Container:" + container.Name);
}
Console.WriteLine();

//List containers in this storage account whose names begin with the prefix "my".
foreach (var container in blobClient.ListContainers("my"))
{
Console.WriteLine("Container:" + container.Name);
}
Console.WriteLine();

//List containers in this storage account whose names begin with the prefix "my",
//and return container metadata.
//Note that requesting the container's metadata as part of the listing operation
//populates the metadata, so it's not necessary to call FetchAttributes().
foreach (var container in blobClient.ListContainers("my", ContainerListingDetails.Metadata))
{
Console.WriteLine("Container:" + container.Name);
//Write out the container's metadata values.
Console.WriteLine("Container metadata:");
foreach (var metadataKey in container.Metadata.Keys)
{
Console.WriteLine("\tMetadata key: " + metadataKey.ToString());
Console.WriteLine("\tMetadata value: " + container.Metadata.Get(metadataKey.ToString()));
}
}
}



 



link http://msdn.microsoft.com/en-us/library/ee758348.aspx

WebService return value

ejemplo

WebServer:

[WebMethod]
        public List<string> getVHD()
        {

       }

 

Cliente/Web

private List<string> getLlistFiles()
        {
            GetListVHD.ArrayOfString listFiles;

            List<string> strlist = new List<string>();
           listFiles = list.getVHD();

            foreach (string str in listFiles)
                strlist.Add(str);

            return strlist;
        }

Download Files from Web [C#]

Download Files from Web [C#]

This example shows how to download files from any website to local disk. The simply way how to download file is to use WebClient class and its method DownloadFile. This method has two parameters, first is the url of the file you want to download and the second parameter ispath to local disk to which you want to save the file.

Download File Synchronously

The following code shows how to download file synchronously. This method blocks the main thread until the file is downloaded or an error occur (in this case the WebException is thrown).

[C#]

using System.Net;

WebClient webClient = new WebClient();
webClient.DownloadFile("http://mysite.com/myfile.txt", @"c:\myfile.txt");


Download File Asynchronously



To download file without blocking the main thread use asynchronous method DownloadFileA­sync. You can also set event handlers to show progress and to detect that the file is downloaded.



[C#]



private void btnDownload_Click(object sender, EventArgs e)
{
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync(new Uri("http://mysite.com/myfile.txt"), @"c:\myfile.txt");
}

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}

private void Completed(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Download completed!");
}


Note: Although you use asynchronous method, it can block the main thread for a while. It's because before the async download itself, it checks the DNS name (in this case „mysite.com“) and this check is done internally by blocking function. If you use directly IP instead of domain name, the DownloadFileAsync method will be fully asynchronous.

CloudDrive.Delete Method (borrar una unidad creada en azure)

 

Windows Azure Platform

Deletes the page blob associated with this Windows Azure drive and all data that it contains.

Namespace: Microsoft.WindowsAzure.StorageClient
Assembly: Microsoft.WindowsAzure.CloudDrive (in microsoft.windowsazure.clouddrive.dll)

 



public void UnmountAndDeleteDrive()
{
// Use the storage emulator.
CloudStorageAccount storageAccount = CloudStorageAccount.DevelopmentStorageAccount;

// Create the Blob service client.
CloudBlobClient client = storageAccount.CreateCloudBlobClient();

// Create the container for the drive if it does not already exist.
CloudBlobContainer container = new CloudBlobContainer("mydrives", client);
container.CreateIfNotExist();

// Get a reference to the page blob that will back the drive.
CloudPageBlob pageBlob = container.GetPageBlobReference("myvhd");

// Return a reference to the drive backed by the specified page blob.
CloudDrive drive = new CloudDrive(pageBlob.Uri, storageAccount.Credentials);

try
{
// Create a 20 MB drive.
drive.Create(20);

// Mount the drive.
string driveLetter = drive.Mount(0, DriveMountOptions.None);

// Write some files to the drive.
for (int i = 0; i < 1000; i++)
{
System.IO.File.WriteAllText(driveLetter + "\\" + i.ToString() + ".txt", "Test");
}

// Write out a file's length.
FileInfo file = new FileInfo(driveLetter + "\\0.txt");
System.Diagnostics.Debug.WriteLine(file.Length);

// Unmount the drive.
drive.Unmount();

// Delete the drive.
drive.Delete();

}
catch (CloudDriveException e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
}



 



link http://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storageclient.clouddrive.delete.aspx