Exemplo n.º 1
0
        protected void Application_Start()
        {
            var savedContext = HttpContext.Current;

            HttpContext.Current = null;

            // This code sets up a handler to update CloudStorageAccount instances when their corresponding
            // configuration settings change in the service configuration file.
            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                // Provide the configSetter with the initial value.
                configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
            });

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            RouteTable.Routes.AddWcfServiceRoute <AuthenticationService>("AuthenticationService");
            RouteTable.Routes.AddWcfServiceRoute <SharedAccessSignatureService>("SharedAccessSignatureService");
            RouteTable.Routes.AddWcfServiceRoute <SamplePushUserRegistrationService>("PushNotificationService");

            var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");

            CreateCloudTables(account.CreateCloudTableClient());

            HttpContext.Current = savedContext;
        }
Exemplo n.º 2
0
        // Constructor - get settings from a hosted service configuration or .NET configuration file.

        public BlobHelper(string configurationSettingName, bool hostedService)
        {
            if (hostedService)
            {
                CloudStorageAccount.SetConfigurationSettingPublisher(
                    (configName, configSettingPublisher) =>
                {
                    var connectionString = RoleEnvironment.GetConfigurationSettingValue(configName);
                    configSettingPublisher(connectionString);
                }
                    );
            }
            else
            {
                CloudStorageAccount.SetConfigurationSettingPublisher(
                    (configName, configSettingPublisher) =>
                {
                    var connectionString = ConfigurationManager.ConnectionStrings[configName].ConnectionString;
                    configSettingPublisher(connectionString);
                }
                    );
            }

            Account = CloudStorageAccount.FromConfigurationSetting(configurationSettingName);

            BlobClient             = Account.CreateCloudBlobClient();
            BlobClient.RetryPolicy = RetryPolicies.Retry(4, TimeSpan.Zero);
        }
Exemplo n.º 3
0
        public override void Run()
        {
            // This is a sample worker implementation. Replace with your logic.
            Trace.WriteLine("RdStorage_WorkerRole entry point called", "Information");

            // initialize the account information
            var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");

            // retrieve a reference to the messages queue
            var queueClient = storageAccount.CreateCloudQueueClient();
            var queue       = queueClient.GetQueueReference("messagequeue");

            // retrieve messages and write them to the compute emulator log
            while (true)
            {
                Thread.Sleep(10000);

                if (queue.Exists())
                {
                    var msg = queue.GetMessage();

                    if (msg != null)
                    {
                        Trace.TraceInformation(string.Format("Message '{0}' processed.", msg.AsString));
                        queue.DeleteMessage(msg);
                    }
                }
            }
        }
Exemplo n.º 4
0
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterOpenAuth();

            if (imageStorePath == null)
            {
                ImageStorePath = WebConfigurationManager.AppSettings["ImageStorePath"];
            }

            // initialize storage account configuration setting publisher
            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                string connectionString = RoleEnvironment.GetConfigurationSettingValue(configName);
                configSetter(connectionString);
            });

            try
            {
                // initialize the local cache for the Azure drive
                LocalResource cache = RoleEnvironment.GetLocalResource("LocalDriveCache");
                CloudDrive.InitializeCache(cache.RootPath + "cache", cache.MaximumSizeInMegabytes);

                // retrieve storage account
                CloudStorageAccount account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");

                // retrieve URI for the page blob that contains the cloud drive from configuration settings
                string imageStoreBlobUri = RoleEnvironment.GetConfigurationSettingValue("ImageStoreBlobUri");

                // unmount any previously mounted drive.
                foreach (var drive in CloudDrive.GetMountedDrives())
                {
                    var mountedDrive = new CloudDrive(drive.Value, account.Credentials);
                    mountedDrive.Unmount();
                }

                // create the Windows Azure drive and its associated page blob
                CloudDrive imageStoreDrive = account.CreateCloudDrive(imageStoreBlobUri);

                if (CloudDrive.GetMountedDrives().Count == 0)
                {
                    try
                    {
                        imageStoreDrive.Create(16);
                    }
                    catch (CloudDriveException)
                    {
                        // drive already exists
                    }
                }

                // mount the drive and initialize the application with the path to the image store on the Azure drive
                Global.ImageStorePath = imageStoreDrive.Mount(cache.MaximumSizeInMegabytes / 2, DriveMountOptions.None);
            }
            catch (CloudDriveException driveException)
            {
                Trace.WriteLine("Error: " + driveException.Message);
            }
        }
Exemplo n.º 5
0
        public static void DeleteArticle(int AnnouncementID)
        {
            var statusMessage = String.Empty;

            try
            {
                var account = CloudStorageAccount.FromConfigurationSetting("TableDataConnectionString");

                var context = new MessageDataServiceContext(account.TableEndpoint.ToString(), account.Credentials);
                while (true)
                {
                    var o = (from message in context.Messages
                             where message.IsNotification == false && message.AnnouncementID == AnnouncementID
                             select message).FirstOrDefault();
                    if (o == null)
                    {
                        return;
                    }
                    context.DeleteObject(o);
                    context.SaveChanges();
                }
            }
            catch (DataServiceRequestException ex)
            {
                statusMessage = "Unable to connect to the table storage server. Please check that the service is running.<br>"
                                + ex.Message;
            }
        }
Exemplo n.º 6
0
        private void InitializeQueueListener()
        {
            Microsoft.WindowsAzure.CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                configSetter(Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.GetConfigurationSettingValue(configName));
            });
            var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            var queueStorage   = storageAccount.CreateCloudQueueClient();
            var queue          = queueStorage.GetQueueReference("myqueue");

            queue.CreateIfNotExist();
            while (true)
            {
                CloudQueueMessage msg = queue.GetMessage();
                if (msg != null)
                {
                    // DO SOMETHING HERE
                    queue.DeleteMessage(msg);
                }
                else
                {
                    System.Threading.Thread.Sleep(1000);
                }
            }
        }
        private void Init(string configurationSettingName)
        {
            if (RoleEnvironment.IsAvailable)
            {
                CloudStorageAccount.SetConfigurationSettingPublisher(
                    (configName, configSettingPublisher) =>
                {
                    var connectionString = RoleEnvironment.GetConfigurationSettingValue(configName);
                    configSettingPublisher(connectionString);
                }
                    );
            }
            else
            {
                CloudStorageAccount.SetConfigurationSettingPublisher(
                    (configName, configSettingPublisher) =>
                {
                    var connectionString = ConfigurationManager.ConnectionStrings[configName].ConnectionString;
                    configSettingPublisher(connectionString);
                }
                    );
            }

            Account = CloudStorageAccount.FromConfigurationSetting(configurationSettingName);

            TableClient             = Account.CreateCloudTableClient();
            TableClient.RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromMilliseconds(100));
        }
        private string CreateBlob(Stream content, string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("blob name can't be null or empty");
            }

            if (content == null)
            {
                throw new ArgumentException("stream is null or emply");
            }

            var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            var blobClient     = storageAccount.CreateCloudBlobClient();

//#warning TODO: find better place for creating the cross domain policy file
//            CreateStorageCrossDomainPolicy(blobClient);

            var container = blobClient.GetContainerReference(ContainerName);

            container.CreateIfNotExist();
            CloudBlob blob = container.GetBlobReference(name);

            blob.UploadFromStream(content);

            return(blob.Uri.AbsoluteUri);
        }
        static PersonTableStorageContext()
        {
            account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            CloudTableClient tableClient = new CloudTableClient(account.TableEndpoint.AbsoluteUri, account.Credentials);

            tableClient.CreateTableIfNotExist(TableName);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Initializes the queue.
        /// </summary>
        private void InitializeQueue()
        {
            bool storageInitialized = false;

            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) => {
                configSetter(GetConnectionString("DataConnectionString"));
            });

            var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");

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

            queue = queueStorage.GetQueueReference("cybernanny");
            Trace.TraceInformation("Creating queue...");

            while (!storageInitialized)
            {
                try {
                    queue.CreateIfNotExist();
                    storageInitialized = true;
                } catch (StorageClientException e) {
                    if (e.ErrorCode == StorageErrorCode.TransportError)
                    {
                        Trace.TraceError("Storage services initialization failure. Message:{0}", e.Message);
                        System.Threading.Thread.Sleep(3000);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
Exemplo n.º 11
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            CloudStorageAccount account    = CloudStorageAccount.FromConfigurationSetting("dataConnStr");
            CloudBlobClient     blobClient = account.CreateCloudBlobClient();
            CloudBlobContainer  container  = blobClient.GetContainerReference("testing12");

            container.CreateIfNotExist();

            BlobContainerPermissions containerPermissions = new BlobContainerPermissions();

            containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob;
            container.SetPermissions(containerPermissions);

            var blob = container.GetBlobReference("file.x");

            blob.UploadFromStream(FileUpload1.FileContent);

            Response.Write(blob.Uri.ToString());

            //using (FileStream fs = File.OpenRead(path))
            //{
            //    // Create the Blob and upload the file
            //    var blob = _BlobContainer.GetBlobReference(Guid.NewGuid().ToString() + "/" + filename);
            //    blob.UploadFromStream(fs);

            //    // Set the metadata into the blob
            //    blob.Metadata["FileName"] = filename;
            //    blob.Metadata["Submitter"] = "Automated Encoder";
            //    blob.SetMetadata();

            //    // Set the properties
            //    blob.Properties.ContentType = "video/x-ms-wmv";
            //    blob.SetProperties();
            //}
        }
        public static void PreStart()
        {
            // Configure the default values for the Push Notifications Registration Service:
            // - Anonymous access
            // - Windows Azure Storage Tables as the storage provider
            NotificationServiceContext.Current.Configure(
                c =>
            {
                // TODO: Specify additional authentication rules
                c.AuthenticateRequest = currentRequest => true;

                // TODO: Specify a rule for whether users can access the Management Operations (get, all)
                c.AuthorizeManagementRequest = currentRequest => true;

                // TODO: Specify a rule for authorizing users when registring (register, unregister)
                c.AuthorizeRegistrationRequest = AuthorizeUserRequest;

                // TODO: Replace with your own Windows Azure Storage account name and key, or read it from a configuration file
                CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSettingPublisher) =>
                {
                    var connectionString = ConfigurationManager.AppSettings[configName];
                    configSettingPublisher(connectionString);
                });

                //var act = new CloudStorageAccount(new StorageCredentialsAccountAndKey("ajholwp","DMZ6Gaec53G7EF4u4HcsgUjZCRutx0pKxwi40s+u1DRPwUow+UaZSb1fhbpdTFsDpsuOYMZqai/Bv83suRfVUQ=="), true);
                var act           = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                c.StorageProvider = new WindowsAzureEndpointRepository(act);

                // TODO: Specify the handlers you want for ASP.NET Web API Registration Service (authentication, logging, etc)
                // c.DelegatingHandlers = new[] { // Your DelegatingHandler instances };
            });

            RouteTable.Routes.MapRegistrationServiceRoute("endpoints");
        }
        public AzureVirtualPathProvider(string blobStorageConnection)
        {
            // Setup the connection to Windows Azure Storage
            var cloudStorageAccount = CloudStorageAccount.FromConfigurationSetting(blobStorageConnection);

            CloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
        }
Exemplo n.º 14
0
        public WorkerRole()
        {
            // This code sets up a handler to update CloudStorageAccount instances when their corresponding
            // configuration settings change in the service configuration file.
            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                // Provide the configSetter with the initial value
                configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));

                RoleEnvironment.Changed += (sender, arg) =>
                {
                    if (arg.Changes.OfType <RoleEnvironmentConfigurationSettingChange>()
                        .Any((change) => (change.ConfigurationSettingName == configName)))
                    {
                        // The corresponding configuration setting has changed, propagate the value
                        if (!configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)))
                        {
                            // In this case, the change to the storage account credentials in the
                            // service configuration is significant enough that the role needs to be
                            // recycled in order to use the latest settings. (for example, the
                            // endpoint has changed)
                            RoleEnvironment.RequestRecycle();
                        }
                    }
                };
            });

            this.storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
        }
Exemplo n.º 15
0
        internal static bool InitializeStorage()
        {
            try
            {
                // 仅为测试目的,如果我们不在计算仿真程序中运行该服务,我们始终使用 dev 存储.
                if (RoleEnvironment.IsAvailable)
                {
                    CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
                    {
                        configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
                    });
                    StorageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                }
                else
                {
                    StorageAccount = CloudStorageAccount.DevelopmentStorageAccount;
                }

                CloudBlobClient    blobClient = new CloudBlobClient(StorageAccount.BlobEndpoint, StorageAccount.Credentials);
                CloudBlobContainer container  = blobClient.GetContainerReference("videostories");
                container.CreateIfNotExist();
                CloudQueueClient queueClient = new CloudQueueClient(StorageAccount.QueueEndpoint, StorageAccount.Credentials);
                CloudQueue       queue       = queueClient.GetQueueReference("videostories");
                queue.CreateIfNotExist();
                CloudTableClient tableClient = new CloudTableClient(StorageAccount.TableEndpoint.AbsoluteUri, StorageAccount.Credentials);
                tableClient.CreateTableIfNotExist("Stories");
                return(true);
            }
            catch (Exception ex)
            {
                Trace.Write("错误初始化存储: " + ex.Message, "Error");
                return(false);
            }
        }
Exemplo n.º 16
0
        public override void Run()
        {
            // This is a sample worker implementation. Replace with your logic.
            Trace.WriteLine("NumberWorkerRole entry point called", "Information");

            CloudStorageAccount account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");

            QueueUtilities qutil = new QueueUtilities(account);
            CloudQueue     queue = qutil.CreateQueueIfNotExists("numbers");

            while (true)
            {
                CloudQueueMessage msg = queue.GetMessage();
                if (msg != null)
                {
                    int number = Convert.ToInt32(msg.AsString);
                    Trace.WriteLine(string.Format("Processing number: {0}", number), "Information");
                    number--;
                    if (number > 0)
                    {
                        CloudQueueMessage newmsg = new CloudQueueMessage(number.ToString());
                        queue.AddMessage(newmsg);
                    }

                    queue.DeleteMessage(msg);
                }
                else
                {
                    Thread.Sleep(10000);
                    Trace.WriteLine("Working", "Information");
                }
            }
        }
Exemplo n.º 17
0
        public override bool OnStart()
        {
            DiagnosticMonitor.Start("DiagnosticsConnectionString");

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

            Microsoft.WindowsAzure.CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                string configuration = RoleEnvironment.IsAvailable ?
                                       RoleEnvironment.GetConfigurationSettingValue(configName) :
                                       ConfigurationManager.AppSettings[configName];

                configSetter(configuration);
            });

            StorageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");

            CloudTableClient.CreateTablesFromModel(
                typeof(DataContext),
                StorageAccount.TableEndpoint.AbsoluteUri,
                StorageAccount.Credentials);

            return(base.OnStart());
        }
Exemplo n.º 18
0
        protected static IQueryable <ChirpEntity> Find()
        {
            CloudStorageAccount account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            ChirpContext        context = new ChirpContext(account.TableEndpoint.ToString(), account.Credentials);

            return(context.ChirpEntities);
        }
        /// <summary>
        /// Removes the request.
        /// </summary>
        /// <param name="userIdentifier">The user identifier.</param>
        /// <param name="removeAll">if set to <c>true</c> [remove all].</param>
        /// <returns></returns>
        public bool RemoveRequest(int userIdentifier, bool removeAll, out StringBuilder message)
        {
            var retval = false;

            message = new StringBuilder();

            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) => {
                configSetter(GetConnectionString("DataConnectionString"));
            });


            if (userIdentifier.Equals(Common.AngelId) || userIdentifier.Equals(Common.MeryId))
            {
                var account     = CloudStorageAccount.FromConfigurationSetting(Common.ConnectionString);
                var queueClient = account.CreateCloudQueueClient();
                var queue       = queueClient.GetQueueReference("cybernanny");

                if (queue.RetrieveApproximateMessageCount() > 0)
                {
                    if (!removeAll)
                    {
                        var messageObj = queue.GetMessage();
                        message.Append(messageObj.AsString);
                        queue.DeleteMessage(messageObj);
                    }
                    else
                    {
                        queue.Clear();
                    }
                    retval = true;
                }
            }
            return(retval);
        }
Exemplo n.º 20
0
        private static void InitializeStorage()
        {
            if (_storageInitialized)
            {
                return;
            }

            lock (_locker)
            {
                try
                {
                    var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");

                    _blobStorage = storageAccount.CreateCloudBlobClient();
                    CloudBlobContainer blobContainer = _blobStorage.GetContainerReference("logitems");
                    blobContainer.CreateIfNotExist();

                    _queueStorage = storageAccount.CreateCloudQueueClient();
                    CloudQueue queue = _queueStorage.GetQueueReference("logmessages");
                    queue.CreateIfNotExist();
                }
                catch (System.Net.WebException)
                {
                    throw new System.Net.WebException("Storage services initialization failure. "
                                                      + "Check your storage account configuration settings. If running locally, "
                                                      + "ensure that the Development Storage service is running.");
                }

                _storageInitialized = true;
            }
        }
Exemplo n.º 21
0
        public static void Initialize()
        {
            CloudStorageAccount account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            CloudTableClient    ctc     = account.CreateCloudTableClient();

            ctc.CreateTableIfNotExist(TABLE_NAME);
        }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            Microsoft.WindowsAzure.CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                string configuration = RoleEnvironment.IsAvailable ?
                                       RoleEnvironment.GetConfigurationSettingValue(configName) :
                                       ConfigurationManager.AppSettings[configName];

                configSetter(configuration);
            });

            CloudStorageAccount account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");

            Processor = new Processor(account);

            (new Thread(new ThreadStart(GetResponse))).Start();

            while (true)
            {
                string program = "";

                string line = System.Console.ReadLine();

                while (line != "send")
                {
                    program += line;
                    program += "\r\n";
                    line     = System.Console.ReadLine();
                }

                Processor.SendRequest(program);
            }
        }
Exemplo n.º 23
0
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterOpenAuth();

            // This code sets up a handler to update CloudStorageAccount instances when their corresponding
            // configuration settings change in the service configuration file.
            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                // Provide the configSetter with the initial value
                configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
            });

            /// Create data table from MessageDataServiceContext
            /// It is recommended the data tables should be only created once. It is typically done as a
            /// provisioning step and rarely in application code.
            var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");

            // dynamically create the tables
            CloudTableClient.CreateTablesFromModel(
                typeof(MessageDataServiceContext),
                account.TableEndpoint.AbsoluteUri,
                account.Credentials);
        }
Exemplo n.º 24
0
 private static IAzureStorageConfig CreateCloudStorageConfig()
 {
     DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString");
     CloudStorageAccount.SetConfigurationSettingPublisher(
         (configName, configSetter) => configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)));
     return(AzureStorage.CreateConfig(CloudStorageAccount.FromConfigurationSetting("StorageConnectionString")));
 }
Exemplo n.º 25
0
        public BlobDocumentStorage()
        {
            this.container = ConfigurationManager.AppSettings["blobStorageContainer"];
            var account = CloudStorageAccount.FromConfigurationSetting(ConfigurationManager.AppSettings["DataConnectionString"]);

            this.cloudBlobClient = account.CreateCloudBlobClient();
        }
Exemplo n.º 26
0
        private static CloudBlobClient GetClient()
        {
            CloudStorageAccount account         = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            CloudBlobClient     cloudBlobClient = account.CreateCloudBlobClient();

            return(cloudBlobClient);
        }
Exemplo n.º 27
0
        private static void InitializeStorage()
        {
            if (storageInitialized)
            {
                return;
            }

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

                try                  // инициализируем BLOB-хранилище
                {
                    // read account configuration settings

                    var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");



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

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

                    // create queue for matches
                    queueClient = storageAccount.CreateCloudQueueClient();
                    queue       = queueClient.GetQueueReference("queue");
                    queue.CreateIfNotExist();

                    // раньше DbconnectionString для EntityConnection парсилась RoleEnviroment.GetConfiguration, но парсилась как-то..
                    // плохо. временно заменяю на прямое указание!
                    //db = new DBContext(new EntityConnection(@"metadata=res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl;provider=System.Data.SqlClient;provider connection string='data source=localhost\SQLEXPRESS;initial catalog=WarSpotDB;integrated security=True;multipleactiveresultsets=True;App=EntityFramework'")); // инициализируем базу данных

                    db = new DBContext(Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.GetConfigurationSettingValue("DBConnectionString"));
                }
                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.");
                }
                catch (TypeInitializationException)
                {
                    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;
            }
        }
Exemplo n.º 28
0
        public override bool OnStart()
        {
            DiagnosticMonitor.Start("DiagnosticsConnectionString");

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

            // This code sets up a handler to update CloudStorageAccount instances when their corresponding
            // configuration settings change in the service configuration file.
            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                // Provide the configSetter with the initial value
                configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));

                RoleEnvironment.Changed += (anotherSender, arg) =>
                {
                    if (arg.Changes.OfType <RoleEnvironmentConfigurationSettingChange>()
                        .Any((change) => (change.ConfigurationSettingName == configName)))
                    {
                        // The corresponding configuration setting has changed, propagate the value
                        if (!configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)))
                        {
                            // In this case, the change to the storage account credentials in the
                            // service configuration is significant enough that the role needs to be
                            // recycled in order to use the latest settings. (for example, the
                            // endpoint has changed)
                            RoleEnvironment.RequestRecycle();
                        }
                    }
                };
            });

            var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");

            // Create the table and add some dummy data.
            CloudTableClient tableClient = new CloudTableClient(account.TableEndpoint.AbsoluteUri, account.Credentials);

            tableClient.CreateTableIfNotExist("Person");
            PersonTableStorageContext ctx = new PersonTableStorageContext();
            Person person1 = new Person("DefaultPartition", "Row1")
            {
                Name = "Ared", Age = 24
            };
            Person person2 = new Person("DefaultPartition", "Row2")
            {
                Name = "Lante", Age = 24
            };
            Person person3 = new Person("DefaultPartition", "Row3")
            {
                Name = "Bright", Age = 24
            };

            this.InsertEntityIfNotExist(ctx, person1);
            this.InsertEntityIfNotExist(ctx, person2);
            this.InsertEntityIfNotExist(ctx, person3);

            return(base.OnStart());
        }
Exemplo n.º 29
0
        public FilesDataSource()
        {
            //Init the storage account
            _storageAccount   = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            _cloudTableClient = _storageAccount.CreateCloudTableClient();

            _cloudTableClient.CreateTableIfNotExist("Files");
        }
        private CloudBlobContainer GetContainer()
        {
            // Get a handle on account, create a blob service client and get container proxy
            var account = CloudStorageAccount.FromConfigurationSetting("StorageConnectionString");
            var client  = account.CreateCloudBlobClient();

            return(client.GetContainerReference(RoleEnvironment.GetConfigurationSettingValue("StorageName")));
        }