zoukankan      html  css  js  c++  java
  • Windows Azure Sample

    void Application_Start(object sender, EventArgs e)
            {
                
    // Code that runs on application startup
                Microsoft.WindowsAzure.CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
                {
                    configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
                });
            }

    // ----------------------------------------------------------------------------------
    // Microsoft Developer & Platform Evangelism
    // 
    // Copyright (c) Microsoft Corporation. All rights reserved.
    // 
    // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
    // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
    // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
    // ----------------------------------------------------------------------------------
    // The example companies, organizations, products, domain names,
    // e-mail addresses, logos, people, places, and events depicted
    // herein are fictitious.  No association with any real company,
    // organization, product, domain name, email address, logo, person,
    // places, or events is intended or should be inferred.
    // ----------------------------------------------------------------------------------

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    using System.IO;
    using System.Net;
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.ServiceRuntime;
    using Microsoft.WindowsAzure.StorageClient;
    using GuestBook_Data;

    namespace GuestBook_WebRole
    {
        
    public partial class _Default : System.Web.UI.Page
        {
            
    private static bool storageInitialized = false;
            
    private static object gate = new Object();
            
    private static CloudBlobClient blobStorage;
            
    private static CloudQueueClient queueStorage;

            
    protected void Page_Load(object sender, EventArgs e)
            {
                
    if (!Page.IsPostBack)
                {
                    Timer1.Enabled 
    = true;
                }
            }

            
    protected void SignButton_Click(object sender, EventArgs e)
            {
                
    if (FileUpload1.HasFile)
                {
                    InitializeStorage();

                    
    // upload the image to blob storage
                    string uniqueBlobName = string.Format("guestbookpics/image_{0}{1}", Guid.NewGuid().ToString(), Path.GetExtension(FileUpload1.FileName));
                    CloudBlockBlob blob 
    = blobStorage.GetBlockBlobReference(uniqueBlobName);
                    blob.Properties.ContentType 
    = FileUpload1.PostedFile.ContentType;
                    blob.UploadFromStream(FileUpload1.FileContent);
                    System.Diagnostics.Trace.TraceInformation(
    "Uploaded image '{0}' to blob storage as '{1}'", FileUpload1.FileName, uniqueBlobName);

                    
    // create a new entry in table storage
                    GuestBookEntry entry = new GuestBookEntry() { GuestName = NameTextBox.Text, Message = MessageTextBox.Text, PhotoUrl = blob.Uri.ToString(), ThumbnailUrl = blob.Uri.ToString() };
                    GuestBookDataSource ds 
    = new GuestBookDataSource();
                    ds.AddGuestBookEntry(entry);
                    System.Diagnostics.Trace.TraceInformation(
    "Added entry {0}-{1} in table storage for guest '{2}'", entry.PartitionKey, entry.RowKey, entry.GuestName);

                    
    // queue a message to process the image
                    var queue = queueStorage.GetQueueReference("guestthumbs");
                    var message 
    = new CloudQueueMessage(String.Format("{0},{1},{2}", blob.Uri.ToString(), entry.PartitionKey, entry.RowKey));
                    queue.AddMessage(message);
                    System.Diagnostics.Trace.TraceInformation(
    "Queued message to process blob '{0}'", uniqueBlobName);
                }

                NameTextBox.Text 
    = "";
                MessageTextBox.Text 
    = "";

                DataList1.DataBind();
            }

            
    protected void Timer1_Tick(object sender, EventArgs e)
            {
                DataList1.DataBind();
            }

            
    private void InitializeStorage()
            {
                
    if (storageInitialized)
                {
                    
    return;
                }

                
    lock (gate)
                {
                    
    if (storageInitialized)
                    {
                        
    return;
                    }

                    
    try
                    {
                        
    // read account configuration settings
                        var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");

                        
    // create blob container for images
                        blobStorage = storageAccount.CreateCloudBlobClient();
                        CloudBlobContainer container 
    = blobStorage.GetContainerReference("guestbookpics");
                        container.CreateIfNotExist();

                        
    // configure container for public access
                        var permissions = container.GetPermissions();
                        permissions.PublicAccess 
    = BlobContainerPublicAccessType.Container;
                        container.SetPermissions(permissions);

                        
    // create queue to communicate with worker role
                        queueStorage = storageAccount.CreateCloudQueueClient();
                        CloudQueue queue 
    = queueStorage.GetQueueReference("guestthumbs");
                        queue.CreateIfNotExist();
                    }
                    
    catch (WebException)
                    {
                        
    throw new WebException("Storage services initialization failure. "
                            
    + "Check your storage account configuration settings. If running locally, "
                            
    + "ensure that the Development Storage service is running.");
                    }

                    storageInitialized 
    = true;
                }
            }
        }
    }


    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Net;
    using System.Threading;
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.Diagnostics;
    using Microsoft.WindowsAzure.ServiceRuntime;
    using Microsoft.WindowsAzure.StorageClient;

    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Drawing.Imaging;
    using System.IO;
    using GuestBook_Data;

    namespace GuestBook_WorkerRole
    {
        
    public class WorkerRole : RoleEntryPoint
        {
            
    private CloudQueue queue;
            
    private CloudBlobContainer container;

            
    public void ProcessImage(Stream input, Stream output)
            {
                
    int width;
                
    int height;
                var originalImage 
    = new Bitmap(input);

                
    if (originalImage.Width > originalImage.Height)
                {
                    width 
    = 128;
                    height 
    = 128 * originalImage.Height / originalImage.Width;
                }
                
    else
                {
                    height 
    = 128;
                    width 
    = 128 * originalImage.Width / originalImage.Height;
                }

                var thumbnailImage 
    = new Bitmap(width, height);

                
    using (Graphics graphics = Graphics.FromImage(thumbnailImage))
                {
                    graphics.InterpolationMode 
    = InterpolationMode.HighQualityBicubic;
                    graphics.SmoothingMode 
    = SmoothingMode.AntiAlias;
                    graphics.PixelOffsetMode 
    = PixelOffsetMode.HighQuality;
                    graphics.DrawImage(originalImage, 
    00, width, height);
                }

                thumbnailImage.Save(output, ImageFormat.Jpeg);
            }

            
    public override void Run()
            {
                Trace.TraceInformation(
    "Listening for queue messages...");

                
    while (true)
                {
                    
    try
                    {
                        
    // retrieve a new message from the queue
                        CloudQueueMessage msg = queue.GetMessage();
                        
    if (msg != null)
                        {
                            
    // parse message retrieved from queue
                            var messageParts = msg.AsString.Split(new char[] { ',' });
                            var imageBlobUri 
    = messageParts[0];
                            var partitionKey 
    = messageParts[1];
                            var rowkey 
    = messageParts[2];
                            Trace.TraceInformation(
    "Processing image in blob '{0}'.", imageBlobUri);

                            
    string thumbnailBlobUri = System.Text.RegularExpressions.Regex.Replace(imageBlobUri, "([^\\.]+)(\\.[^\\.]+)?$""$1-thumb$2");

                            CloudBlob inputBlob 
    = container.GetBlobReference(imageBlobUri);
                            CloudBlob outputBlob 
    = container.GetBlobReference(thumbnailBlobUri);

                            
    using (BlobStream input = inputBlob.OpenRead())
                            
    using (BlobStream output = outputBlob.OpenWrite())
                            {
                                ProcessImage(input, output);

                                
    // commit the blob and set its properties
                                output.Commit();
                                outputBlob.Properties.ContentType 
    = "image/jpeg";
                                outputBlob.SetProperties();

                                
    // update the entry in table storage to point to the thumbnail
                                GuestBookDataSource ds = new GuestBookDataSource();
                                ds.UpdateImageThumbnail(partitionKey, rowkey, thumbnailBlobUri);

                                
    // remove message from queue
                                queue.DeleteMessage(msg);

                                Trace.TraceInformation(
    "Generated thumbnail in blob '{0}'.", thumbnailBlobUri);
                            }
                        }
                        
    else
                        {
                            System.Threading.Thread.Sleep(
    1000);
                        }
                    }
                    
    catch (StorageClientException e)
                    {
                        Trace.TraceError(
    "Exception when processing queue item. Message: '{0}'", e.Message);
                        System.Threading.Thread.Sleep(
    5000);
                    }
                }
            }

            
    public override bool OnStart()
            {
                
    // Set the maximum number of concurrent connections 
                ServicePointManager.DefaultConnectionLimit = 12;

                
    // For information on handling configuration changes
                
    // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

                
    // read storage account configuration settings
                CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
                {
                    configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
                });
                var storageAccount 
    = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");

                
    // initialize blob storage
                CloudBlobClient blobStorage = storageAccount.CreateCloudBlobClient();
                container 
    = blobStorage.GetContainerReference("guestbookpics");

                
    // initialize queue storage 
                CloudQueueClient queueStorage = storageAccount.CreateCloudQueueClient();
                queue 
    = queueStorage.GetQueueReference("guestthumbs");

                Trace.TraceInformation(
    "Creating container and queue...");

                
    bool storageInitialized = false;
                
    while (!storageInitialized)
                {
                    
    try
                    {
                        
    // create the blob container and allow public access
                        container.CreateIfNotExist();
                        var permissions 
    = container.GetPermissions();
                        permissions.PublicAccess 
    = BlobContainerPublicAccessType.Container;
                        container.SetPermissions(permissions);

                        
    // create the message queue(s)
                        queue.CreateIfNotExist();

                        storageInitialized 
    = true;
                    }
                    
    catch (StorageClientException e)
                    {
                        
    if (e.ErrorCode == StorageErrorCode.TransportError)
                        {
                            Trace.TraceError(
    "Storage services initialization failure. "
                              
    + "Check your storage account configuration settings. If running locally, "
                              
    + "ensure that the Development Storage service is running. Message: '{0}'", e.Message);
                            System.Threading.Thread.Sleep(
    5000);
                        }
                        
    else
                        {
                            
    throw;
                        }
                    }
                }

                
    return base.OnStart();
            }
        }
    }



    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.StorageClient;

    namespace GuestBook_Data
    {
        
    public class GuestBookDataSource
        {
            
    private static CloudStorageAccount storageAccount;
            
    private GuestBookDataContext context;

            
    static GuestBookDataSource()
            {
                storageAccount 
    = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");

                CloudTableClient.CreateTablesFromModel(
                    
    typeof(GuestBookDataContext),
                    storageAccount.TableEndpoint.AbsoluteUri,
                    storageAccount.Credentials);
            }

            
    public GuestBookDataSource()
            {
                
    this.context = new GuestBookDataContext(storageAccount.TableEndpoint.AbsoluteUri, storageAccount.Credentials);
                
    this.context.RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromSeconds(1));
            }

            
    public IEnumerable<GuestBookEntry> GetGuestBookEntries()
            {
                var results 
    = from g in this.context.GuestBookEntry
                              
    where g.PartitionKey == DateTime.UtcNow.ToString("MMddyyyy")
                              select g;
                
    return results;
            }

            
    public void AddGuestBookEntry(GuestBookEntry newItem)
            {
                
    this.context.AddObject("GuestBookEntry", newItem);
                
    this.context.SaveChanges();
            }

            
    public void UpdateImageThumbnail(string partitionKey, string rowKey, string thumbUrl)
            {
                var results 
    = from g in this.context.GuestBookEntry
                              
    where g.PartitionKey == partitionKey && g.RowKey == rowKey
                              select g;

                var entry 
    = results.FirstOrDefault<GuestBookEntry>();
                entry.ThumbnailUrl 
    = thumbUrl;
                
    this.context.UpdateObject(entry);
                
    this.context.SaveChanges();
            }
        }
    }



    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace GuestBook_Data
    {
        
    public class GuestBookDataContext
            : Microsoft.WindowsAzure.StorageClient.TableServiceContext
        {
            
    public GuestBookDataContext(string baseAddress, Microsoft.WindowsAzure.StorageCredentials credentials)
                : 
    base(baseAddress, credentials)
            { }

            
    public IQueryable<GuestBookEntry> GuestBookEntry
            {
                
    get
                {
                    
    return this.CreateQuery<GuestBookEntry>("GuestBookEntry");
                }
            }
        }
    }



    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.WindowsAzure.StorageClient;

    namespace GuestBook_Data
    {
        
    public class GuestBookEntry
            : Microsoft.WindowsAzure.StorageClient.TableServiceEntity
        {
            
    public GuestBookEntry()
            {
                PartitionKey 
    = DateTime.UtcNow.ToString("MMddyyyy");

                
    // Row key allows sorting, so we make sure the rows come back in time order.
                RowKey = string.Format("{0:10}_{1}", DateTime.MaxValue.Ticks - DateTime.Now.Ticks, Guid.NewGuid());
            }

            
    public string Message { getset; }
            
    public string GuestName { getset; }
            
    public string PhotoUrl { getset; }
            
    public string ThumbnailUrl { getset; }
        }
    }

     <?xml version="1.0" encoding="utf-8"?>

    <ServiceConfiguration serviceName="GuestBook" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration" osFamily="1" osVersion="*">
      
    <Role name="GuestBook_WebRole">
        
    <Instances count="1" />
        
    <ConfigurationSettings>
          
    <Setting name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" value="UseDevelopmentStorage=true" />
          
    <Setting name="DataConnectionString" value="UseDevelopmentStorage=true" />
        
    </ConfigurationSettings>
      
    </Role>
      
    <Role name="GuestBook_WorkerRole">
        
    <Instances count="1" />
        
    <ConfigurationSettings>
          
    <Setting name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" value="UseDevelopmentStorage=true" />
          
    <Setting name="DataConnectionString" value="UseDevelopmentStorage=true" />
        
    </ConfigurationSettings>
      
    </Role>
    </ServiceConfiguration>


    <?xml version="1.0" encoding="utf-8"?>
    <ServiceDefinition name="GuestBook" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition">
      
    <WebRole name="GuestBook_WebRole">
        
    <Sites>
          
    <Site name="Web">
            
    <Bindings>
              
    <Binding name="Endpoint1" endpointName="Endpoint1" />
            
    </Bindings>
          
    </Site>
        
    </Sites>
        
    <Endpoints>
          
    <InputEndpoint name="Endpoint1" protocol="http" port="80" />
        
    </Endpoints>
        
    <Imports>
          
    <Import moduleName="Diagnostics" />
        
    </Imports>
        
    <ConfigurationSettings>
          
    <Setting name="DataConnectionString" />
        
    </ConfigurationSettings>
      
    </WebRole>
      
    <WorkerRole name="GuestBook_WorkerRole">
        
    <Imports>
          
    <Import moduleName="Diagnostics" />
        
    </Imports>
        
    <ConfigurationSettings>
          
    <Setting name="DataConnectionString" />
        
    </ConfigurationSettings>
      
    </WorkerRole>
    </ServiceDefinition>
  • 相关阅读:
    JVM(二)-运行时数据区
    JVM(一)-JVM入门
    java设计模式之观察者模式
    开散列表
    闭散列表
    VTWORAY 常用配置
    kubernetes 提示1 node(s) had taints that the pod didn't tolerate
    SOCKS5转PPTP VTWORAY配置文件与IPTables配置文件
    【Docker】多阶段构建
    【Docker】容器内存扩容
  • 原文地址:https://www.cnblogs.com/RobotTech/p/2097136.html
Copyright © 2011-2022 走看看