domingo, 31 de julio de 2011

drag and drop from treeview to listview using C#

 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DragFromListToTree
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//listView1.AllowDrop = true;
treeView1.AllowDrop = true;
}

private void listView1_ItemDrag(object sender, ItemDragEventArgs e)
{
listView1.DoDragDrop(e.Item, DragDropEffects.Move);

}

private void treeView1_DragEnter(object sender, DragEventArgs e)
{
// this code can be in DragOver also
if (e.Data.GetDataPresent(typeof(ListViewItem)))
e.Effect = DragDropEffects.Move;
}

private void treeView1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(ListViewItem)))
{

ListViewItem li = (ListViewItem)e.Data.GetData(typeof(ListViewItem));

bool dupplicate = false;

foreach (TreeNode tn in treeView1.Nodes)
{
if (tn.Text == li.Text) dupplicate = true;
}

if (!dupplicate)
{
treeView1.Nodes.Add(li.Text);
listView1.Items.Remove(li);
}
}
}

}
}

viernes, 29 de julio de 2011

Obtener las unidades del disco duro HD

Resultado

C:

D:

obtener las unidades del disco duro

 

using System.Management;

 

System.Management.ManagementObjectSearcher ms = new System.Management.ManagementObjectSearcher("SELECT * FROM win32_logicaldisk");
            foreach (ManagementObject mo in ms.Get())
            {

                 path = mo["deviceid"].ToString() + "\\";
                try
                {

                    string[] filePaths = Directory.GetDirectories(path);

                    this.ListBox1.Items.Add(path);

                    if (filePaths.Length > 0)
                    {
                        foreach (string dir in filePaths)
                        {
                            this.ListBox1.Items.Add(dir);
                        }
                    }
                }
                catch { }

            }

 

 

link http://stackoverflow.com/questions/4084402/get-hard-disk-serial-number

ASP.NET MapPath Resolves Virtual, Physical Paths (path)

 

You need to use MapPath to resolve virtual paths and physical paths. You run the ASP.NET development server on your local machine, but the paths on it are not the same as they are on your server. Here we use MapPath to find physical paths and file locations, using the C# programming language.

Introduction

First, in ASP.NET the ~ tilde indicates the root of a virtual path. We need the tilde because otherwise ASP.NET can't figure out if a path is absolute or relative. Let's look at some virtual paths and what they might map to.

Virtual paths

~/App_Data/Sample.xml
~/
~/Map.txt

Physical paths

C:\Website\Files\Sample.xml
C:\Website\Default.aspx
C:\Website\Map.txt


Use MapPath method



You can call MapPath in any C# file in your ASP.NET website. You may want to include the System.Web namespace first, but this is not required. Make sure you are looking at a C# file in your ASP.NET project and then add some code that looks similar to parts of the following.



Example code that uses MapPath [C#]

using System;
using System.Web;

/// <summary>
/// This is an example code-behind file you can put in App_Code.
/// It shows examples of using MapPath in code-behind easily.
/// </summary>

public class Example
{
public Example()
{
// This will locate the Example.xml file in the App_Data folder.
// ... (App_Data is a good place to put data files.)

string a = HttpContext.Current.Server.MapPath("~/App_Data/Example.xml");

// This will locate the Example.txt file in the root directory.
// ... This can be used in a file in any directory in the application.

string b = HttpContext.Current.Request.MapPath("~/Example.txt");
}
}


Using Server.MapPath. Here we note that the Server.MapPath does the same thing as the Request.MapPath method. In this example, the two versions will do the same thing. There may be some differences in different usage scenarios, but in those cases a more detailed guide would be helpful. The two methods are interchangeable in most ASP.NET projects.

lunes, 25 de julio de 2011

Using Windows Azure Drive Part 1: migrate your data to the Cloud (Create .vhd file)

 

 

 

This month, we announced the Beta Release of Windows Azure Drive (a.k.a. XDrive), a technology that allows you to mount a VHD (Virtual Hard Drive) into a Windows Azure instance and access it as if it was a locally attached NTFS drive.

There are many applications for this technology, and in this post I would like to illustrate one of them: migrating an existing on-premise application, that uses regular Windows file access APIs, into the cloud, with no impact on the existing I/O code, thanks to Windows Azure Drive. There will really be two parts in this post:

  1. How to create a VHD locally, and upload it into the cloud so that it can be used as an XDrive; this part is important because the XDrive must be created as a Page Blob, a special kind of Windows Azure Blob
  2. How to modify your existing code to use the XDrive; we will see that once the XDrive is set up, the rest of your code will think it is dealing with a regular NTFS drive

This is the first part, where the most interesting part has actually been contributed by my colleague Stéphane Crozatier from the ISV DPE Team here in France, who programmed the Page Blob Upload Tool that is the key to making your data available as an XDrive in the cloud. Thanks Stéphane!

Introduction

First, let’s have a look at my application. It is a very simple Windows application that allows you to browse a directory of PDF files using thumbnails. The idea is to port this application to the cloud, so that you can browse the PDF files, hosted in Windows Azure, from a Web browser.

image

This application has two important characteristics, beyond its ugliness, in our case:

  1. It has some existing file & directory I/O code, just regular .NET System.IO stuff, that is used to navigate through directories, finding PDF files, and driving thumbnails generation.
  2. It uses a third-party Win32 DLL and P/Invoke to generate the thumbnails (the well-known GhostscriptOpen Source library, which gives you a PostScript /PDF interpreter and viewer); I am usingGhostscriptSharp, Matthew Ephraim’s P/Invoke wrapper for Ghostscript, to access the DLL from my C# application.

Of course, we could port our System.IO stuff to use Windows Azure Blobs instead; in my case, it would be quite easy, because the code is very simple! But this may not be the case of your existing applications. Furthermore, the case of the Ghostscript DLL is more complicated: I really don’t want to port this library, written in C, to Windows Azure Storage! It will be much simpler for me to just simulate a disk drive using XDrive, and I can keep my DLL as it is. Besides, if you have existing third-party closed source libraries, you may not have a choice.

How to migrate your data into an XDrive

I could start with an empty XDrive, creating it directly from my Azure application, and there are some examples of this in the Windows Azure Drive White Paper we have published. But my problem is different: my existing data (my directories of PDF files) and my application are linked: they work together, and I want to migrate them both into the cloud.

So, I am going to create a local VHD, where I will create the directory structure I need and copy my data, and I will upload this VHD to Windows Azure as a Page Blob, so it can be later mounted is an XDrive.

Creating the VHD

Creating a new VHD and mounting it is easy in Windows 7. If you want to use the VHD as an XDrive, you need to pay attention to the following:

  • The VHD should be of fixed size
  • It must not be smaller than 16 MB
  • It must not be bigger than 1 TB
  • Do not use exotic sizes, just use a multiple of 1 MB

Here are the steps using the Windows 7 Disk Management Tool.

Just type “format” in the start menu and select “Create and format hard disk partitions”:

image

Select “Create VHD” from the “Action” menu:

image

Specify the path, size and format:

image

Click OK, and the VHD will be created and attached automatically:

image

Now you need to initialize it, like any other disk; right-click on the disk an select “Initialize Disk”:

image

Select “MBR” (the default) and click OK:

image

Now, right-click on the partition and select “New Simple Volume…”:

image

Just follow the defaults in the wizard that follows. You will assign a drive letter to the new drive, then format it as NTFS. Give it a volume name if you want and make sure to select “Perform a quick format”.

You now have a brand new Virtual Hard Drive, attached locally like a regular hard drive:

image

I will now copy my data into this virtual hard drive; I will create three directories for the various PDF files I want to browse, and copy a number of PDF files in each directory:

image

Once I am done, I can detach the VHD from the Disk Management tool, and my VHD is ready to be uploaded:

image 

Uploading the VHD

Now, the really fun part begins! All we need to do is upload the VHD in Windows Azure Storage as a Blob, right? So why not use any of the nice graphical tools at our disposal, like the Azure Storage Explorer from CodePlex, Cerebrata Cloud Storage Studio, or CloudBerry Explorer for Azure Blob Storage? Easy: the VHD must be uploaded as a Page Blob, and none of the graphical tools can handle Page Blob at this time! So, we need to build our own upload tool.

Here I must thank my colleague Stéphane Crozatier from the ISV DPE Team here in France, who did all the hard work of figuring out how to do this. All the code is his!

Basically, the first thing we need to do is to create a Page Blob using the StorageClient API from the Windows Azure SDK:



CloudBlobClient blobStorage = account.CreateCloudBlobClient();
CloudPageBlob blob = blobStorage.GetPageBlobReference(blobUri);
blob.Properties.ContentType = "binary/octet-stream";
blob.Create(blobSize);



 



Then, we need to upload the whole file page by page, using the Put Page operation, which is surfaced as theCloudPageBlob.WritePages method in the Storage Client API. Because WritePages requires a Stream as input, we will use a MemoryStream to hold the pages of data we read from the file.








int pageSize = 1024 * 1024;
int numPages = (int)(file.Length / pageSize);
byte[] page = new byte[pageSize];
using (MemoryStream stmPage = new MemoryStream(page))
{
// process all pages until last
for (int i = 0; i < numPages; i++)
{
// write page to storage
file.Read(page, 0, pageSize);
stmPage.Seek(0, SeekOrigin.Begin);
blob.WritePages(stmPage, i * pageSize);
}

// process last page
if (blobSize > numPages * pageSize)
{
int remain = (int)(blobSize - (numPages * pageSize));
page = new byte[remain]; // allocate a clean buffer, padding with zero

using (MemoryStream stmLast = new MemoryStream(page))
{
// write page to storage
file.Read(page, 0, remain);
stmLast.Seek(0, SeekOrigin.Begin);
blob.WritePages(stmLast, numPages * pageSize);
}
}
}



Here is the complete version of Stéphane’s Page Blob Upload tool (UploadPageBlob.zip):




It is a Visual Studio 2010 solution, ready to use. Here is how to use it:




  • in the app.config file (or in UploadPageBlob.exe.config), enter your Windows Azure Storage Account credentials:

    • <add key="StorageAccount" value="DefaultEndpointsProtocol=http;AccountName=...;AccountKey=..." />


    • These credentials can be found in the administration page for your storage account, in the “Cloud Storage” section. AccountName is the first part of your storage URL (i.e. if your endpoint is foo.blob.core.windows.net, then your AccountName is foo). AccountKey is the associated Primary Access Key.




  • Build the solution, open a command window and go to the output directory; the syntax for the tool is:

    • UploadPageBlob <filename> <blobUrl>


    • The tool will report nicely on the upload status.





image



 



 



link http://blogs.msdn.com/b/tconte/archive/2010/02/26/using-windows-azure-drive-part-1-migrate-your-data-to-the-cloud.aspx

Click to Drag, Zoom, and Copy - PictureBox

 

 

Click and Drag to Zoom

Introduction

This control was originally developed to mimic some existing software that my company was using to view and process medical claims. The original plan was to develop a PictureBox that would allow the users to draw a box on the image and then zoom in on that point. It was immediately apparent that this would be no easy task.

Changes

The PictureBoxEx still uses .NET 1.1 to make it more compatible with current and future projects, but has been completely rewritten.

This control is a completely new control, it is no longer based on a PictureBox but a ScrollableControl. Making this switch was necessary to create a control that was both flexible and fast. When drawing the drag window, the old control was slow to build the image and refresh, whereas the new control is very smooth.

This new version also contains the ability to add annotations to the images. These annotations can be colored, resized to match the image's current zoom, and best of all are XmlSerializable, so they can be saved to file and retrieved later.

Scrolling was also added to this new control. The control now has the ability to be scrolled vertically and horizontally, by both the keys and the mouse. Scrolling the wheel causes the image to be scrolled vertically, but if you hold the control key while scrolling the mouse wheel, the image can now be scrolled horizontally. The arrow keys plus Home, End, PageUp, PageDown can all be used to scroll the image. Because the control is unable to receive and hold direct focus, the focus can shift from control to control on the same form. So to make use of the key scrolling, it is best to make this PictureBoxEx the only control on the form. (If anyone knows how to improve this limitation, I would love to hear about it.)

Also the current zoom of the control can be changed by scrolling the mouse wheel while holding the shift key down.

Features

  1. Click and drag window to zoom or copy
  2. Parentless design (New)
  3. Annotate (Includes custom cursor) (New)
  4. Diagnostics mode (New)
  5. Zoom and scroll with the mouse wheel (New)
  6. Scroll with keys (Works best if the only control on form) (New)

Custom Properties

Most of the controls custom properties are available through the designer.

  • AllowDrag: Indicates whether or not the user should be allowed to drag and copy or zoom
  • CurrentZoom: Controls the PictureBox's current zoom.
  • DefaultZoom: Controls the PictureBox's default zoom.
  • DiagnosticMode: Set to true to display diagnostics information.
  • DoubleClickRestore: Controls the PictureBox's ability to restore the image to the default zoom on double-click.
  • DragOptions: Controls the PictureBox's drag options. (Copy, Zoom, or Prompt)
  • DragWindowColor: Controls the PictureBox's drag window color.
  • DragWindowMinimum: Controls the PictureBox's minimum invokable drag window size.
  • DragWindowPattern: The dash pattern that is used by the control when drawing the drag window.
  • DrawMode: Controls the imaging filter that will be applied to the image if it is resized. (InterpolationMode)
  • MaximumZoom: Controls the maximum allowed zoom.
  • MinimumZoom: Controls the minimum allowed zoom.

The Code

The following code is used by GenerateResizedImage to generate the resized image from the backup which is created when the Image property of the control is set. The creating of the resized image happens regardless of the current zoom, even if it's 1. The reason it's generated anyway is because the control can't work with images of an indexed pixel format. So it's just easier to convert the images straight away.



int resizedWidth  = Convert.ToInt32(backup.Width  * _currentZoom);
int resizedHeight = Convert.ToInt32(backup.Height * _currentZoom);
resized = new Bitmap(resizedWidth, resizedHeight);

// Drag the backup image onto the resized image

using (Graphics g = Graphics.FromImage(resized))
{
g.InterpolationMode = (_currentZoom < 1F) ?
_drawMode : InterpolationMode.Default;

Rectangle srceRect =
new Rectangle(0, 0, backup.Width, backup.Height);
Rectangle destRect =
new Rectangle(0, 0, resized.Width, resized.Height);

g.DrawImage(backup, destRect, srceRect, GraphicsUnit.Pixel);

// Add any annotations to the resized image

DrawAnnotations(g);
}



Determining where the zoom should occur requires a lot of math. The first step it to compensate for the current zoom and the current scroll position. Then, it needs to be determined which part of the drag window is larger in proportion to the size of the control, and enlarge that section to fill the control while centering the remainder.








// The zoom window will never be proportional to the container, so one

// side will get filled while the other gets centered. The larger % will

// determine which gets filled, and which gets centered

float xRatio = (float)Width / (float)dragWindowSave.Width;
float yRatio = (float)Height / (float)dragWindowSave.Height;

float largerRatio;
int xAdjust = 0;
int yAdjust = 0;

largerRatio = (xRatio < yRatio) ? xRatio : yRatio;

// The cumulative zoom cannot exceed the maximum zoom;

if ((largerRatio * _currentZoom) > _maximumZoom)
largerRatio = _maximumZoom / _currentZoom;

if (dragWindowSave.Width * largerRatio > Width)
largerRatio = (float)Width / (float)dragWindowSave.Width;

if (dragWindowSave.Height * largerRatio > Height)
largerRatio = (float)Height / (float)dragWindowSave.Height;

yAdjust = Convert.ToInt32(
((float)Height - (float)dragWindowSave.Height * largerRatio) / 2F);
xAdjust = Convert.ToInt32(
((float)Width - (float)dragWindowSave.Width * largerRatio) / 2F);

int xScrollPos = Math.Max(Convert.ToInt32(((float)-AutoScrollPosition.X +
(float)dragWindowSave.X) * largerRatio) - xAdjust, 0);
int yScrollPos = Math.Max(Convert.ToInt32(((float)-AutoScrollPosition.Y +
(float)dragWindowSave.Y) * largerRatio) - yAdjust, 0);

CurrentZoom *= largerRatio;



 



Using the Control



The control is very much like a PictureBox. All that really needs to be done is to add the control to a form and set its Image property.




  1. Add a reference to the Build DLL.


  2. Add the control to your form.


  3. Set the desired control properties.


  4. Set the control's Image property.



Lessons Learned



This control has an event that fires after the image has been changed. If subscribers of this event take a lot of time or processor power, it will appear to have a negative impact on the performance of this control.



Without a backup image, the zooming process (in and out) will degrade image quality.



Known Issues




  1. Some designer mode instability.


  2. Some issues with the border styles not being drawn correctly.



History



This control was developed for Trusted Plans Service Corp. Tacoma WA.




  • Version 1 - released 3/6/2006.


  • Version 2 - released 12/12/2006.



 



 



link http://www.codeproject.com/KB/miscctrl/ClickAndDragPictureBox.aspx

CloudDrive.InitializeCache Method (Multiples Conecciones)

 

 

 

Initializes the optional read cache for any subsequently mounted drives associated with the role instance.

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

  Usage

Visual Basic

Dim cachePath As String
Dim totalCacheSize As Integer

CloudDrive.InitializeCache(cachePath, totalCacheSize)

  Syntax

Visual Basic

Public Shared Sub InitializeCache ( _
cachePath As String, _
totalCacheSize As Integer _
)

C#

public static void InitializeCache (
string cachePath,
int totalCacheSize
)

C++

public:
static void InitializeCache (
String^ cachePath,
int totalCacheSize
)

J#

public static void InitializeCache (
String cachePath,
int totalCacheSize
)

JScript

public static function InitializeCache (
cachePath : String,
totalCacheSize : int
)

Parameters


cachePath

The local file system path to the directory containing the cache.



totalCacheSize

The total cache size, in megabytes.


  Example

The following snippet from a ServiceDefinition.csdef file specifies a local resource named LocalDriveCache.






<LocalResources>
     <LocalStorage name="LocalDriveCache" sizeInMB="2048" cleanOnRoleRecycle="false" />
</LocalResources>
 

The following code example creates and mounts three drives, allocating cache space to the first two and none to the third.

C#





public void InitializeDriveCache()
{
// Get a reference to the local resource.
LocalResource localResource = RoleEnvironment.GetLocalResource("LocalDriveCache");

// Initialize the drive cache.
CloudDrive.InitializeCache(localResource.RootPath, localResource.MaximumSizeInMegabytes);

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

int cacheSize = (int)Math.Round((double)localResource.MaximumSizeInMegabytes / 2;

// Create and mount three drives, allocating portions of the cache
// to the first two and none to the third.
CloudDrive drive1 = new CloudDrive(container.GetPageBlobReference("myvhd_A").Uri, storageAccount.Credentials);
drive1.Create(500);
drive1.Mount(cacheSize, DriveMountOptions.None);

CloudDrive drive2 = new CloudDrive(container.GetPageBlobReference("myvhd_B").Uri, storageAccount.Credentials);
drive2.Create(500);
drive2.Mount(cacheSize, DriveMountOptions.None);

CloudDrive drive3 = new CloudDrive(container.GetPageBlobReference("myvhd_C").Uri, storageAccount.Credentials);
drive3.Create(500);
drive3.Mount(0, DriveMountOptions.None);

// List each drive letter and associated page blob.
foreach (var item in CloudDrive.GetMountedDrives())
{
System.Diagnostics.Debug.WriteLine("Drive letter: " + item.Key);
System.Diagnostics.Debug.WriteLine("Page blob URI: " + item.Value);
}
}

 

  Remarks

A role instance running in Windows Azure may have an optional write-through cache for all drives that are mounted by the instance. Each role instance may allocate a single cache. The InitializeCache method allocates total cache space for all drives mounted by the role instance. When a given drive is mounted, you can choose to allocate a portion of the total cache space to that drive. If you intend to allocate cache space for a given drive, you must call InitializeCache before you mount the drive. When you call InitializeCache, be sure to take into account the total cache size you expect to need for all drives to be mounted.

Note that you can also mount a drive with no cache specified. If you opt not to allocate cache space for a drive, then it's not necessary to call InitializeCache.

The local file system path specified for the cachePath parameter should be the root path for a local storage resource defined in the service definition file. A local storage resource reserves space on the local file system for the role instance to use at runtime. See How to Configure Local Storage Resources for details on declaring a local storage resource for the cache. Note that when you define the local storage resource for the cache, you should set the CleanOnRoleRecycle attribute to false, so that the cache data persists when the role is recycled.

noteNote

Data in the cache may not be persisted in the event of a transient hardware failure that requires the role instance to be moved to different hardware in Windows Azure.

The maximum size permitted for the local storage resource depends on the size of the VM allocated for the role instance. The VM size is specified in the service definition file. For details on choosing a VM size and the amount of available local storage space for each, see How to Configure Virtual Machine Sizes. Note that the local storage space allocated to the VM is the total amount for the instance, so the total space allocated for all local storage resources, including the drive cache, must not exceed the total allowed for the VM.

To initialize the cache, return a reference to the local storage resource by calling the GetLocalResource method, then use the values returned by the RootPath and MaximumSizeInMegaBytes properties of the local resource to initialize the cache:

LocalResource localCache = RoleEnvironment.GetLocalResource("MyAzureDriveCache");
CloudDrive.InitializeCache(localCache.RootPath, localCache.MaximumSizeInMegabytes);

If your code calls InitializeCache each time the role instance starts, it's recommended that you initialize the cache with the same parameters each time.

 


 


link http://207.46.16.248/en-us/library/microsoft.windowsazure.storageclient.clouddrive.initializecache.aspx

CloudDrive.Create Method (HD Local)

 

Windows Azure Platform

Creates a single-partition, NTFS-formatted Virtual Hard Disk (VHD) page blob to back the Windows Azure drive.

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

Parameters
sizeInMB

The size of the drive to create. The minimum size permitted is 16 MB. The maximum size permitted is 1 TB (the maximum size permitted for a page blob).

Example

The following example creates and mounts a Windows Azure drive.


public void CreateAndMountDrive()
{
// 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 64 MB drive.
drive.Create(64);

// 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");
}
}
catch (CloudDriveException e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
}




Remarks



The Create method creates a page blob at the location specified when the reference to the CloudDrive object was created. The container for the page blob must exist before you call the Create method.



noteNote



If the blob exists, the Create method will fail with a CloudDriveException. To prevent your role from recycling, ensure that you handle this exception properly and do not create a drive that already exists.



To mount a drive using an existing blob or snapshot, create a reference to a CloudDrive object using the URI to the existing blob, then call the Mount method without calling Create.



The Windows Azure drive is created as a fixed VHD within the page blob. Note that the drive format requires some space, so you will not have access to the full amount of space that you allocate for the drive.



noteNote



The Windows Azure development environment provides a simulation of a Windows Azure drive which does not rely on the Windows Azure storage emulator. If your code is running in the development environment, you will not see an actual page blob created in the local Blob service.



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

CloudBlobContainer.ListBlobs Method ()

 

 

Windows Azure Platform

Returns an enumerable collection of the blobs in the container.

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

 

Return Value

An enumerable collection of objects that implement IListBlobItem.

Example

 

The following code example lists blobs in a container first hierarchically, and then using a flat blob listing. Note that the two listings will differ only if the blobs in the container include a delimiter character in their names, and therefore constitute a virtual directory structure.

 



static void ListBlobsInContainer(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));

//Get a reference to the container.
CloudBlobContainer container = blobClient.GetContainerReference("myblobs");

//List blobs and directories in this container hierarchically (which is the default listing).
foreach (var blobItem in container.ListBlobs())
{
Console.WriteLine(blobItem.Uri);
}
Console.WriteLine();

//List blobs in this container using a flat listing.
BlobRequestOptions options = new BlobRequestOptions();
options.UseFlatBlobListing = true;

//List snapshots, which requires a flat blob listing.
options.BlobListingDetails = BlobListingDetails.Snapshots;

foreach (var blobItem in container.ListBlobs(options))
{
Console.WriteLine(blobItem.Uri);
}
}



 



Remarks



The types of objects returned by the ListBlobs method depend on the type of listing that is being performed. If the UseFlatBlobListing property is set to true, the listing will return an enumerable collection ofCloudBlob objects. If UseFlatBlobListing is set to false (the default value), the listing may return a collection containing CloudBlob objects and CloudBlobDirectory objects. The latter case provides a convenience for subsequent enumerations over a virtual blob hierarchy.



 



link http://msdn.microsoft.com/en-us/library/ee772878.aspx#Y100

Inicio rápido de código: Crear una aplicación que almacena un archivo en el almacenamiento de Windows Azure

 

 

 

 

Actualizado: mayo de 2011

Los siguientes pasos describen cómo crear una aplicación de consola que usa la API de servicios de almacenamiento de Windows Azure. Concretamente este ejemplo cargará un archivo en el servicio de blob de Windows Azure.

Este ejemplo no se implementa en Windows Azure; en su lugar, le demuestra cómo llamar a la biblioteca de cliente de almacenamiento de Windows Azure a través de una aplicación de consola independiente.

Antes de continuar asegúrese de que cumple los requisitos previos enumerados en Inicio rápido del código de Windows Azure. Si aún no tiene una suscripción de Windows Azure, puede avanzar en este tema hasta el paso 10 para cargar un archivo en el servicio de blob local en el que se ejecuta el emulador de almacenamiento de Windows Azure.

 

  1. Inicie Microsoft Visual Studio 2010.

  2. En el menú Archivo, haga clic en Nuevo y, a continuación, haga clic en Proyecto.

  3. En el cuadro de diálogo Nuevo proyecto, navegue a Plantillas instaladas, Visual C# y haga clic en Windows.

  4. Haga clic en Aplicación de consola. Elija .NET Framework 4 en la lista desplegable. Si es necesario, modifique el campo Ubicación, que indica donde se almacenará la solución. Para los propósitos de este ejemplo, use StorageSample como nombre del proyecto. Haga clic en Aceptar para cerrar el cuadro de diálogo Nuevo proyecto.

  5. En el menú Proyecto, haga clic en Agregar referencia. En la pestaña Examinar del cuadro de diálogo Agregar referencia, navegue a la ubicación donde están instaladas las bibliotecas de referencia de Windows Azure SDK, asegúrese de usar la versión más reciente. Por ejemplo, C:\Archivos de programa\Windows Azure SDK\v1.4\ref\. Seleccione Microsoft.WindowsAzure.StorageClient.dll y haga clic en Aceptar.

  6. Modifique Program.cs de forma que contenga el siguiente código:

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.StorageClient; namespace StorageSample { class Program { static void Main(string[] args) { try { // Variables for the cloud storage objects. CloudStorageAccount cloudStorageAccount; CloudBlobClient blobClient; CloudBlobContainer blobContainer; BlobContainerPermissions containerPermissions; CloudBlob blob; // Use the local storage account. cloudStorageAccount = CloudStorageAccount.DevelopmentStorageAccount; // If you want to use Windows Azure cloud storage account, use the following // code (after uncommenting) instead of the code above. // cloudStorageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=your_storage_account_name;AccountKey=your_storage_account_key"); // Create the blob client, which provides // authenticated access to the Blob service. blobClient = cloudStorageAccount.CreateCloudBlobClient(); // Get the container reference. blobContainer = blobClient.GetContainerReference("mycontainer"); // Create the container if it does not exist. blobContainer.CreateIfNotExist(); // Set permissions on the container. containerPermissions = new BlobContainerPermissions(); // This sample sets the container to have public blobs. Your application // needs may be different. See the documentation for BlobContainerPermissions // for more information about blob container permissions. containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob; blobContainer.SetPermissions(containerPermissions); // Get a reference to the blob. blob = blobContainer.GetBlobReference("myfile.txt"); // Upload a file from the local system to the blob. Console.WriteLine("Starting file upload"); blob.UploadFile(@"c:\myfiles\myfile.txt"); // File from local storage. Console.WriteLine("File upload complete to blob " + blob.Uri); } catch (StorageClientException e) { Console.WriteLine("Storage client error encountered: " + e.Message); // Exit the application with exit code 1. System.Environment.Exit(1); } catch (Exception e) { Console.WriteLine("Error encountered: " + e.Message); // Exit the application with exit code 1. System.Environment.Exit(1); } finally { // Exit the application. System.Environment.Exit(0); } } } }




  7. Cree un archivo en el equipo local denominado c:\myfiles\myfile.txt. Alternativamente, use un archivo existente, pero cambie el siguiente código para hacer referencia al archivo existente, no ac:\myfiles\myfile.txt:








    blob.UploadFile(@"c:\myfiles\myfile.txt");  // File from local storage.




  8. Guarde Program.cs.


  9. Puesto que el código usa el servicio de blob local, inicie el emulador de almacenamiento de Windows Azure. En Windows, haga clic en el icono Inicio de Windows, haga clic en Todos los programas, haga clic en Windows Azure SDK v1.4 y haga clic en Emulador de almacenamiento. Alternativamente, si el icono Emulador de Windows Azure está en la barra de tareas, puede iniciar el emulador de almacenamiento si hace clic con el botón secundario en el icono Emulador de Windows Azure y, a continuación, en Iniciar el emulador de almacenamiento.


  10. En el menú Depurar, haga clic en Iniciar sin depurar. Suponiendo que no se produzca ningún error de compilación ni del equipo cliente, el programa debería ejecutarse ahora correctamente. Copie el URI mostrado por la aplicación en el explorador; debería mostrarse el archivo que cargó en el servicio de blob local, ya que está usando la cuenta de almacenamiento local. Para especificar la cuenta de almacenamiento local se usó el siguiente código:








cloudStorageAccount = CloudStorageAccount.DevelopmentStorageAccount;



Para obtener más información sobre el emulador de almacenamiento, vea Configuring and Using the Storage Emulator with Visual Studio.



11. Ahora preparemos el código para cargar el archivo en la cuenta de almacenamiento de Windows Azure, en lugar de cargarlo en la cuenta de almacenamiento local. Si aún no lo ha hecho, cree una cuenta de almacenamiento de Windows Azure siguiendo las instrucciones de Crear una cuenta de almacenamiento.



12. En Program.cs, marque como comentario la siguiente línea de código, dado que va a usar una cuenta de almacenamiento de Windows Azure, no una de almacenamiento de desarrollo:








// cloudStorageAccount = CloudStorageAccount.DevelopmentStorageAccount;




     



    13. Modifique el código de Program.cs para usar la información de la cuenta de almacenamiento. En esta sección de código se necesitan los valores propios de su conexión, que especifican la cadena de conexión que se debe usar para el almacenamiento de Windows Azure:








    cloudStorageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=your_storage_account_name;AccountKey=your_storage_account_key");




 



Asegúrese de que esta línea de código ya no está marcada como comentario. Modifique los valores asignados a your_storage_account_name y your_storage_account_key para usar su nombre de cuenta de almacenamiento y la clave de acceso de la cuenta de almacenamiento, respectivamente. Puede usar el Portal de administración de la plataforma Windows Azure, http://windows.azure.com, para determinar ambos valores. Específicamente, en http://windows.azure.com, puede navegar a Servicios hospedados, cuentas de almacenamiento y CDN y, a continuación, hacer clic en Cuentas de almacenamiento para ver los nombres de cuenta de almacenamiento enumerados para su suscripción o suscripciones. Haga clic en una cuenta de almacenamiento para ver la página de propiedades de las cuentas de almacenamiento. A continuación se muestra la página de propiedades de las cuentas de almacenamiento, con rótulos que indican dónde debería mostrarse el nombre de la cuenta de almacenamiento y la clave de acceso primaria:



 



Propiedades de la cuenta de almacenamiento



En el código anterior, reemplace el texto your_storage_account_name con el nombre de la cuenta de almacenamiento. Reemplace your_storage_account_key con el valor de clave de acceso de almacenamiento primaria o secundaria. Para obtener más información sobre las cadenas de conexión, vea Cómo configurar cadenas de conexión.



 



securitySeguridadNota



Asegúrese de que mantiene en secreto las claves de cuenta de almacenamiento. Proteja la aplicación y el código fuente, incluido el archivo Program.cs, ya que ahora contiene las credenciales de la cuenta de almacenamiento.



14. Guarde Program.cs.



15. En el menú Depurar, haga clic en Iniciar sin depurar. Suponiendo que no se produzca ningún error de compilación ni del equipo cliente, el programa debería ejecutarse ahora correctamente. Copie el URI mostrado por la aplicación en el explorador; debería mostrarse el archivo que cargó en la cuenta de almacenamiento de Windows Azure.



 



El código muestra adquiere una instancia de la clase CloudStorageAccount, que encapsula las credenciales necesarias para autenticar una solicitud en los servicios de almacenamiento. A continuación, este objeto se usa para crear una instancia de la clase CloudBlobClient, que proporciona acceso al servicio de blob. Con la instancia de CloudBlobClient, el ejemplo adquiere una referencia a un contenedor de blob denominadomycontainer y lo crea si no existe. El permiso del contenedor se establece para permitir el acceso anónimo en el nivel de blob. Para obtener información sobre los diversos tipos de permisos disponibles para un contenedor, vea BlobContainerPermissions. Finalmente, el ejemplo carga un archivo local en el blob denominado myfile.txt mediante una llamada al método UploadFile. Observe que no es necesario que el nombre del blob sea el mismo que el del archivo local.



Además de poder ver el blob mediante su URI, puede verlo en Visual Studio. Para obtener información sobre cómo ver el blob en Visual Studio, vea Browsing Storage Resources with the Windows Azure Storage Explorer. Asimismo, hay disponible una variedad de software de visualización de almacenamiento de Windows Azure de otros fabricantes que se puede encontrar mediante búsquedas en línea.



Tal y como cabe esperar de una entidad de almacenamiento, hay muchos métodos y propiedades disponibles para los blobs. Por ejemplo, puede cargar el texto en un blob a través del método UploadText o descargar un blob en un archivo a través del método DownloadToFile. Si desea eliminar el blob que cargó, llame al método Delete. Para obtener más información sobre los métodos y propiedades de los blobs, veaCloudBlob.



De igual forma, hay muchos métodos y propiedades para los contenedores. Por ejemplo, puede enumerar los blobs en un contenedor mediante el método ListBlobs o eliminar un contenedor a través del métodoDelete. Para obtener más información sobre los métodos y propiedades de los contenedores, vea CloudBlobContainer.



Aparte de CloudBlobClient, los otros tipos de clientes que se pueden adquirir a través de una instancia de la clase CloudStorageAccount son CloudTableClient y CloudQueueClient, que se usan para las operaciones de las tablas y colas de Windows Azure, respectivamente. Para obtener más información sobre la biblioteca administrada de .NET para los servicios de almacenamiento de Windows Azure, veaMicrosoft.WindowsAzure.StorageClient.



Además de la biblioteca administrada de .NET proporcionada por la API de servicios de almacenamiento de Windows Azure, también se proporciona una API de REST para la funcionalidad de almacenamiento. Para obtener más información, vea Windows Azure Storage Services REST API Reference.





link http://msdn.microsoft.com/es-es/library/gg651129.aspx

CloudBlob.DownloadToFile Method (String)

 

Windows Azure Platform

Downloads the blob's contents to a file.

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

 

Example

static void DownloadBlobToFile(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));

//Return a reference to the blob.
CloudBlob blob = blobClient.GetBlobReference("mycontainer/myblob.txt");

//Download the blob to a local file.
blob.DownloadToFile("c:\\mylocalblob.txt");
}
Community Content

This method uses the default timeout of 90 seconds.   If you download large blobs, and especially if you download them over the Internet (e.g. into a client app), you should probably use the other overload and calculate timeout depending on blob size.   For example:

blob.FetchAttributes(); // Get blob metadata, including length
blob.DownloadToFile(..., new BlobRequestOptions { Timeout = TimeSpan.FromMinutes(Math.Max(1, blob.Properties.Length / 1024*1024)) }); // Allow 1 minute per MB
 
Link http://msdn.microsoft.com/en-us/library/ee772800.aspx