示例#1
0
        public override void Run()
        {
            Log("SolrMasterHostWorkerRole Run() called", "Information");

            while (true)
            {
                Thread.Sleep(10000);
                Log("Working", "Information");

                if ((_solrProcess != null) && (_solrProcess.HasExited == true))
                {
                    Log("Solr Process Exited. Hence recycling master role.", "Information");
                    RoleEnvironment.RequestRecycle();
                    return;
                }
            }
        }
示例#2
0
        private void InstallPackages()
        {
            Tracer.WriteLine("InstallPackages", "Information");

            bool alwaysInstallPackages = bool.Parse(RoleEnvironment.GetConfigurationSettingValue("AlwaysInstallPackages"));

            Tracer.WriteLine(string.Format("AlwaysInstallPackages: {0}", alwaysInstallPackages), "Information");

            string workingDirectory = GetWorkingDirectory();

            // Retrieve the semicolon delimitted list of zip file packages and install them
            string[] packages = RoleEnvironment.GetConfigurationSettingValue(PACKAGES).Split(';');
            foreach (string package in packages)
            {
                try
                {
                    if (package != string.Empty)
                    {
                        // Parse out the container\file pair
                        string[] fields = package.Split(new char[] { '/', '\\' }, 2);

                        string containerName = fields[0];
                        string packageName   = fields[1];
                        if (packageName == "*")
                        {
                            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue(DATA_CONNECTION_STRING));
                            CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();
                            var container = blobClient.GetContainerReference(containerName);
                            foreach (var blobListItem in container.ListBlobs().OrderBy(x => x.Uri.ToString()))
                            {
                                var blob = container.GetBlobReferenceFromServer(blobListItem.Uri.ToString());
                                InstallPackageIfNewer(alwaysInstallPackages, workingDirectory, containerName, blob.Name);
                            }
                        }
                        else
                        {
                            InstallPackageIfNewer(alwaysInstallPackages, workingDirectory, containerName, packageName);
                        }
                    }
                }
                catch (Exception e)
                {
                    Tracer.WriteLine(string.Format("Package \"{0}\" failed to install, {1}", package, e), "Information");
                }
            }
        }
示例#3
0
        public override bool OnStart()
        {
            Log("SolrSlaveHostWorkerRole Start() called", "Information");

            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;

            RoleEnvironment.Changing += (sender, arg) =>
            {
                RoleEnvironment.RequestRecycle();
            };

            InitDiagnostics();
            StartSolr();

            return(base.OnStart());
        }
        protected void Load_Data()
        {
#if AZURE
            //Access the storage account
            var storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("fiftyonedegrees"));
            //Create the service context to access the table
            var serviceContext = new TableServiceContext(storageAccount.TableEndpoint.ToString(), storageAccount.Credentials);

            //Getting the table entries
            foreach (var row in serviceContext.CreateQuery <LogMessageEntity>("log"))    //"log" - the name of the table you wish to see
            {
                OutBox.Text += row.Message;
            }
#else
            OutBox.Text = "This page will only work when compiled for use with Windows Azure";
#endif
        }
        public virtual string GetCloudSetting(string settingName)
        {
            string value = null;

            try
            {
                if (RoleEnvironment.IsAvailable)
                {
                    value = RoleEnvironment.GetConfigurationSettingValue(settingName);
                }
            }
            catch (Exception)
            {
                // Not in the role environment or config setting not found...
            }
            return(value);
        }
        public void InitializeStorage()
        {
            // summary
            // get image queue and blob container using credentials from .cscfg file.

            // Open storage account using credentials from .cscfg file.
            var storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));

            // Get context object for working with blobs, and
            // set a default retry policy appropriate for a web user interface.
            var blobClient = storageAccount.CreateCloudBlobClient();

            blobClient.DefaultRequestOptions.RetryPolicy = new LinearRetry(TimeSpan.FromSeconds(3), 3);

            // Get a reference to the blob container.
            imagesBlobContainer = blobClient.GetContainerReference("scoreimages");
        }
示例#7
0
        public void WriteEntry(string eventName, string notes, string label)
        {
            try
            {
                string tableName = RoleEnvironment.GetConfigurationSettingValue("LogTableName");

                CloudTable table = cloudTableClient.GetTableReference(tableName);
                table.CreateIfNotExists();

                TableOperation insertOperation = TableOperation.Insert(new LogEntry(eventName, notes, label));
                table.Execute(insertOperation);
            }
            catch (Exception e)
            {
                Tracer.WriteLine(e.ToString(), "Critical");
            }
        }
示例#8
0
        private static string TryGetConfigurationSetting(string configName)
        {
            string ret = null;

            try
            {
                if (RoleEnvironment.IsAvailable)
                {
                    ret = RoleEnvironment.GetConfigurationSettingValue(configName);
                }
            }
            catch (RoleEnvironmentException)
            {
                return(null);
            }
            return(ret);
        }
示例#9
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
                {
                    configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
                });
            }
            ;
            CloudStorageAccount account    = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            CloudBlobClient     blobClient = account.CreateCloudBlobClient();
            CloudBlobContainer  container  =
                blobClient.GetContainerReference("ornekcontainer");

            container.Create();
        }
示例#10
0
 //Jean: Refactored, moved from Data Management component
 public static Action <string, Func <string, bool> > GetConfigurationSettingPublisher()
 {
     try
     {
         if (RoleEnvironment.IsAvailable)
         {
             return((configName, configSetter) =>
                    configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)));
         }
     }
     catch (Exception)
     {
         // Compatibility with VisualStudio 2013
     }
     return((configName, configSetter) =>
            configSetter(ConfigurationManager.AppSettings[configName]));
 }
    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.
        bool result = base.OnStart();

        _storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));
        var queueClient = _storageAccount.CreateCloudQueueClient();

        _pushQueue = queueClient.GetQueueReference("pushes");
        _pushQueue.CreateIfNotExists();
        CreatePushBroker();
        Trace.TraceInformation("Foo.PushProcess has been started");
        return(result);
    }
        protected void Application_Start()
        {
            Microsoft.WindowsAzure.CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
            });

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            this.LoadProducts();
        }
示例#13
0
        public static void SendStatusEmail(string emailAddress, Guid jobID, int iteration)
        {
            SmtpClient client = new SmtpClient(RoleEnvironment.GetConfigurationSettingValue("mailSmtpHost"), int.Parse(RoleEnvironment.GetConfigurationSettingValue("mailSmtpPort")))
            {
                Credentials = new NetworkCredential(RoleEnvironment.GetConfigurationSettingValue("mailSendingAddress"), RoleEnvironment.GetConfigurationSettingValue("mailSendingPassword")),
                EnableSsl   = bool.Parse(RoleEnvironment.GetConfigurationSettingValue("mailSmtpSsl"))
            };

            try
            {
                client.Send(RoleEnvironment.GetConfigurationSettingValue("mailSendingAddress"), emailAddress, string.Format("CloudClustering job {0}", jobID), string.Format("CloudClustering job {0} has begun iteration {1}.", jobID, iteration));
            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.WriteLine("Failed to send status email: " + e.ToString());
            }
        }
示例#14
0
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            int totalStubjectCount = Convert.ToInt32(RoleEnvironment.GetConfigurationSettingValue("SubjectCount"));

            if (string.IsNullOrEmpty(Name))
            {
                yield return(new ValidationResult("Student name is Required"));
            }
            else if (ObtainedMarks < 0)
            {
                yield return(new ValidationResult("Invalid Obtained Marks"));
            }
            else if (ObtainedMarks > (totalStubjectCount * 100))
            {
                yield return(new ValidationResult("Obtained Marks should be less then Total Marks"));
            }
        }
示例#15
0
        // before deployment:
        public MyNoteContext() : base(RoleEnvironment.GetConfigurationSettingValue("MyNoteContext"))
            // locally
            //public MyNoteContext() : base(("MyNoteContext"))
        {
            string connString;

            //try
            //{
            //    connString = RoleEnvironment.GetConfigurationSettingValue("MyNoteContext");
            //}
            //catch
            //{
            //   connString = "MyNoteContext";
            //}

            // Database.Connection  = new  = connString;
        }
示例#16
0
        private static int GetSleepTimeFromConfig()
        {
            int sleepTime;

            if (!int.TryParse(RoleEnvironment.GetConfigurationSettingValue("WorkerSleepTime"), out sleepTime))
            {
                sleepTime = 0;
            }

            // polling less than a second seems too eager
            if (sleepTime < 1000)
            {
                sleepTime = 2000;
            }

            return(sleepTime);
        }
示例#17
0
        /// <summary>
        /// Query node mapping data from node mapping table
        /// </summary>
        /// <returns></returns>
        private Dictionary <string, string> GetNodeMappingData()
        {
            try
            {
                string      dataConnectionString = RoleEnvironment.GetConfigurationSettingValue(SchedulerConfigNames.DataConnectionString);
                string      nodeMappingTableName = RoleEnvironment.GetConfigurationSettingValue(SchedulerConfigNames.NodeMapping);
                NodeMapping nodeMapping          = new NodeMapping(CloudStorageAccount.Parse(dataConnectionString), nodeMappingTableName);

                // Following GetLogicalNameIPMapping calls RefreshMapping, so we don't need to call it beforehand.
                return(nodeMapping.GetLogicalNameIPMapping());
            }
            catch (Exception e)
            {
                TraceHelper.TraceError("0", "[NodeMappingCache] .GetNodeMappingData: Failed to get node mapping. {0}", e);
                return(null);
            }
        }
        /// <summary>
        /// Gets the value of the named setting configured in the ServiceConfiguration.cscfg file.
        /// </summary>
        /// <param name="settingName">The name of the setting.</param>
        /// <returns>The setting value, or string.Empty if the setting is not found.</returns>
        internal static string GetConfigurationSettingValue(string settingName)
        {
            string result;

            try
            {
                result = RoleEnvironment.GetConfigurationSettingValue(settingName);
            }
            catch (RoleEnvironmentException)
            {
                // The setting was not found.
                System.Diagnostics.Trace.WriteLine("WebRole environment diagnostics error: " + settingName + " not found.");
                result = string.Empty;
            }

            return(result);
        }
        public async Task Initialize()
        {
            defaultConsumerGroup = eventHubClient.GetConsumerGroup("workerrole");
            string blobConnectionString = RoleEnvironment.GetConfigurationSettingValue("AzureStorage");

            eventProcessorHost = new EventProcessorHost(
                "singleworker",
                eventHubClient.Path,
                defaultConsumerGroup.GroupName,
                RoleEnvironment.GetConfigurationSettingValue("Microsoft.ServiceBus.ConnectionString"),
                blobConnectionString);
            client = CloudStorageAccount.Parse(blobConnectionString).CreateCloudTableClient();
            table  = client.GetTableReference("TwitterItem");
            await table.CreateIfNotExistsAsync();

            await eventProcessorHost.RegisterEventProcessorFactoryAsync(new TwitterEventProcessorFactory(OnEventHubMessagesReveived));
        }
示例#20
0
        public override bool OnStart()
        {
            var config = DiagnosticMonitor.GetDefaultInitialConfiguration();

            var cloudStorageAccount =
                CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString"));

            TimeSpan transferPeriod;

            if (!TimeSpan.TryParse(RoleEnvironment.GetConfigurationSettingValue("Diagnostics.ScheduledTransferPeriod"), out transferPeriod))
            {
                transferPeriod = TimeSpan.FromMinutes(1);
            }

            TimeSpan sampleRate;

            if (!TimeSpan.TryParse(RoleEnvironment.GetConfigurationSettingValue("Diagnostics.PerformanceCounterSampleRate"), out sampleRate))
            {
                sampleRate = TimeSpan.FromSeconds(30);
            }

            LogLevel logLevel;

            if (!Enum.TryParse <LogLevel>(RoleEnvironment.GetConfigurationSettingValue("Diagnostics.LogLevelFilter"), out logLevel))
            {
                logLevel = LogLevel.Verbose;
            }

            // Setup performance counters
            config.PerformanceCounters.DataSources.Add(
                new PerformanceCounterConfiguration
            {
                CounterSpecifier = @"\Processor(_Total)\% Processor Time",
                SampleRate       = sampleRate
            });
            config.PerformanceCounters.ScheduledTransferPeriod = transferPeriod;

            // Setup logs
            config.Logs.ScheduledTransferPeriod         = transferPeriod;
            config.Logs.ScheduledTransferLogLevelFilter = logLevel;

            DiagnosticMonitor.Start(cloudStorageAccount, config);

            return(base.OnStart());
        }
        protected void NewDrive_Click(object sender, EventArgs e)
        {
            if (RoleEnvironment.IsAvailable)
            {
                // retrieve storage account
                CloudStorageAccount account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");

                // build page blob URI for the new cloud drive by changing the extension in the original URI
                string imageStoreBlobUri = RoleEnvironment.GetConfigurationSettingValue("ImageStoreBlobUri");
                string cloneStoreBlobUri = Path.ChangeExtension(imageStoreBlobUri, "bak");

                // create drive and its associated page blob
                CloudDrive clonedDrive = account.CreateCloudDrive(cloneStoreBlobUri);
                if (this.MountedDrives.Items.Count < 2)
                {
                    try
                    {
                        clonedDrive.Create(16);
                    }
                    catch (CloudDriveException)
                    {
                        // cloud drive already exists
                    }

                    // mount the drive and retrieve its path
                    LocalResource cache           = RoleEnvironment.GetLocalResource("LocalDriveCache");
                    string        clonedStorePath = clonedDrive.Mount(cache.MaximumSizeInMegabytes / 2, DriveMountOptions.None);

                    // copy the contents from the original drive to the new drive
                    foreach (string sourceFileName in Directory.GetFiles(Global.ImageStorePath, "*.*").Where(name => name.EndsWith(".jpg") || name.EndsWith(".png")))
                    {
                        string destinationFileName = Path.Combine(clonedStorePath, Path.GetFileName(sourceFileName));
                        File.Copy(sourceFileName, destinationFileName, true);
                    }

                    this.SelectImageStore(clonedStorePath);
                }
                else
                {
                    clonedDrive.Unmount();
                    clonedDrive.Delete();
                    this.SelectImageStore(Global.ImageStorePath);
                }
            }
        }
        private void CreateOnceContainerAndQueue()
        {
            if (s_createdContainerAndQueue)
            {
                return;
            }
            lock (s_lock)
            {
                if (s_createdContainerAndQueue)
                {
                    return;
                }

                try
                {
                    var storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"));

                    blobStorage = storageAccount.CreateCloudBlobClient();
                    CloudBlobContainer container = blobStorage.GetContainerReference("photogallery");

                    container.CreateIfNotExist();

                    var permissions = container.GetPermissions();

                    permissions.PublicAccess = BlobContainerPublicAccessType.Container;

                    container.SetPermissions(permissions);

                    queueStorage = storageAccount.CreateCloudQueueClient();
                    CloudQueue queue = queueStorage.GetQueueReference("thumbnailmaker");

                    queue.CreateIfNotExist();
                }
                catch (WebException)
                {
                    // display a nice error message if the local development storage tool is not running or if there is
                    // an error in the account configuration that causes this exception
                    throw new WebException("The Windows Azure storage services cannot be contacted " +
                                           "via the current account configuration or the local development storage tool is not running. " +
                                           "Please start the development storage tool if you run the service locally!");
                }

                s_createdContainerAndQueue = true;
            }
        }
示例#23
0
        public override bool OnStart()
        {
            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            CloudStorageAccount.SetConfigurationSettingPublisher(
                (name, publisher) =>
            {
                var connectionString = RoleEnvironment.GetConfigurationSettingValue(name);
                publisher(connectionString);
            }
                );

            var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            AzureQueue <UserRegistrationMessage> queue = new AzureQueue <UserRegistrationMessage>(account);

            queue.EnsureExist();

            AzureBlobContainer <RegistrationTokenEntity> registrationBlob = new AzureBlobContainer <RegistrationTokenEntity>(account, true);

            registrationBlob.EnsureExist();

            // We could do the 'worker role' portion here aslo
            //Task.Factory.StartNew(() =>
            //{
            //    while (true)
            //    {
            //        try
            //        {
            //            var message = queue.GetMessage();
            //            if (message != null)
            //            {
            //                var entity = new RegistrationTokenEntity();
            //                entity.RegistrationToken = (new Random()).Next().ToString();
            //                registrationBlob.Save(message.ContainerId, entity);
            //                queue.DeleteMessage(message);
            //            }
            //        }
            //        catch { }
            //        Thread.Sleep(5000);
            //    }
            //});

            return(base.OnStart());
        }
示例#24
0
        private static void SendMessage(EMailMessage eMessage)
        {
            var smtpSettings = RoleEnvironment.GetConfigurationSettingValue("SmtpSettings");
            var parts        = smtpSettings.Split(',', ';');

            if (parts.Length < 6)
            {
                Trace.TraceError("SmtpSettings must contain 6 parts: host, [port#], [<ssl>], from, [user],[password].");
                return;
            }
            int i           = 0;
            var host        = parts[i++].Trim();
            var port        = parts[i++].Trim();
            var ssl         = parts[i++].Trim();
            var from        = parts[i++].Trim();
            var accountName = parts[i++].Trim();
            var password    = parts[i];
            int portNumber;

            int.TryParse(port, out portNumber);

            var message = new MailMessage(from, eMessage.To, eMessage.Subject, eMessage.Body)
            {
                IsBodyHtml = eMessage.IsBodyHtml
            };
            var smtpClient = new SmtpClient(host)
            {
                EnableSsl             = ssl.ToLowerInvariant() == "ssl",
                UseDefaultCredentials = false,
            };

            if (portNumber != 0)
            {
                smtpClient.Port = portNumber;
            }
            if (!string.IsNullOrEmpty(accountName))
            {
                smtpClient.Credentials = new NetworkCredential(accountName, password);
            }
            else
            {
                Trace.TraceError("Anonymous SMTP authentication will be applied.");
            }
            smtpClient.Send(message);
        }
示例#25
0
        /// <summary>
        /// Used to delete all records
        /// </summary>
        public void DeleteRecords()
        {
            try
            {
                // Retrieve storage account from connection string
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue(Constatns.StorageAccountConnectionString));

                // Create the table client
                CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

                //get table references
                CloudTable updateTable = tableClient.GetTableReference("updatedcityrecord");
                CloudTable globalTable = tableClient.GetTableReference("globalvariables");

                // Get the data service context
                TableServiceContext serviceContext = tableClient.GetTableServiceContext();

                //// Specify a partition query
                List <UpdatedCityRecord> cityRecordsList =
                    (from e in serviceContext.CreateQuery <UpdatedCityRecord>("updatedcityrecord")
                     select e).ToList();

                foreach (UpdatedCityRecord city in cityRecordsList)
                {
                    city.ETag = "*";
                    TableOperation deleteOperation = TableOperation.Delete(city);
                    updateTable.Execute(deleteOperation);
                }

                //// Specify a partition query
                List <GlobalVariables> global =
                    (from e in serviceContext.CreateQuery <GlobalVariables>("globalvariables")
                     select e).ToList();
                foreach (GlobalVariables city in global)
                {
                    city.ETag = "*";
                    TableOperation deleteOperation = TableOperation.Delete(city);
                    globalTable.Execute(deleteOperation);
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
            }
        }
示例#26
0
        /// <summary>
        /// Get a MongoServerSettings object that can then be used to create a connection to the
        /// MongoDB Replica Set. Note this assumes the name of the replica ser role is ReplicaSetRole.
        /// The connection settings should be cached on the client side and should only be obtained
        /// if there is a connect exception.
        /// </summary>
        /// <returns>A MongoServerSettings object that corresponds to the replica set instances</returns>
        /// <example>var server = MongoServer.Create(MongoDBAzureHelper.GetReplicaSetSettings());</example>
        /// <example>var setting = MongoDBAzureHelper.GetReplicaSetSettings();
        /// setting.SlaveOk = true;
        /// var server = MongoServer.Create(setting);</example>
        public static MongoServerSettings GetReplicaSetSettings()
        {
            var settings = new MongoServerSettings();
            // TODO - Should only have 1 setting across both roles
            var replicaSetName = RoleEnvironment.GetConfigurationSettingValue(ReplicaSetNameSetting).ToLower();

            settings.ReplicaSetName = replicaSetName;

            ReadOnlyCollection <RoleInstance> workerRoleInstances = null;

            try
            {
                workerRoleInstances = RoleEnvironment.Roles[RoleEnvironment.CurrentRoleInstance.Role.Name].Instances;
            }
            catch (KeyNotFoundException ke)
            {
                throw new ReplicaSetEnvironmentException(
                          string.Format("The MongoDB worker role should be called {0}", RoleEnvironment.CurrentRoleInstance.Role.Name),
                          ke);
            }
            catch (Exception e)
            {
                throw new ReplicaSetEnvironmentException(
                          "Exception when trying to obtain worker role instances",
                          e);
            }

            int replicaSetRoleCount = workerRoleInstances.Count;
            var servers             = new List <MongoServerAddress>();

            foreach (var instance in workerRoleInstances)
            {
                var endpoint         = instance.InstanceEndpoints[MongodPortSetting].IPEndpoint;
                var instanceIdString = instance.Id;
                int instanceId       = int.Parse(instanceIdString.Substring(instanceIdString.LastIndexOf("_") + 1));
                var server           = new MongoServerAddress(
                    endpoint.Address.ToString(),
                    (RoleEnvironment.IsEmulated ? endpoint.Port + instanceId : endpoint.Port)
                    );
                servers.Add(server);
            }
            settings.Servers        = servers;
            settings.ConnectionMode = ConnectionMode.ReplicaSet;
            return(settings);
        }
示例#27
0
        public MembershipCreateStatus CreateUser(UserData userInfo)
        {
            if (String.IsNullOrEmpty(userInfo.Email))
            {
                throw new ArgumentException("Value cannot be null or empty.", "Email");
            }
            if (String.IsNullOrEmpty(userInfo.Password))
            {
                throw new ArgumentException("Value cannot be null or empty.", "Password");
            }
            if (String.IsNullOrEmpty(userInfo.FirstName))
            {
                throw new ArgumentException("Value cannot be null or empty.", "First Name");
            }
            if (String.IsNullOrEmpty(userInfo.LastName))
            {
                throw new ArgumentException("Value cannot be null or empty.", "First Name");
            }

            if (String.IsNullOrEmpty(userInfo.Role))
            {
                userInfo.Role = "Guest";
            }

            userInfo.LastLogin = new DateTime(1900, 1, 1);
            userInfo.Email     = userInfo.Email.ToLower();

            var account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"));
            var context = account.CreateCloudTableClient().GetDataServiceContext();

            var currentUser = context.CreateQuery <UserData>("Users")
                              .Where(user => user.PartitionKey == "wedding" &&
                                     user.Email == userInfo.Email)
                              .FirstOrDefault();

            if (currentUser != null)
            {
                return(MembershipCreateStatus.DuplicateUserName);
            }

            context.AddObject("Users", userInfo);
            context.SaveChangesWithRetries();

            return(MembershipCreateStatus.Success);
        }
示例#28
0
        private static void InstallPackages()
        {
            Console.WriteLine("InstallPackages", "Information");

            var workingDirectory = GetWorkingDirectory();

            // Retrieve the semicolon delimitted list of zip file packages and install them
            var packages = RoleEnvironment.GetConfigurationSettingValue(PACKAGES).Split(';', ',');

            foreach (string package in packages)
            {
                Console.WriteLine("Installing Package " + package);
                try
                {
                    if (!string.IsNullOrWhiteSpace(package))
                    {
                        // Parse out the container\file pair
                        var fields = package.Trim().Split(new char[] { '/', '\\' }, 2);

                        var containerName = fields[0];
                        var packageName   = fields[1];

                        if (packageName == "*")
                        {
                            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue(DATA_CONNECTION_STRING));
                            CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();
                            var container = blobClient.GetContainerReference(containerName);
                            foreach (var blobListItem in container.ListBlobs().OrderBy(x => x.Uri.ToString()))
                            {
                                var blob = container.GetBlobReference(blobListItem.Uri.ToString());
                                InstallPackageIfNewer(true, workingDirectory, containerName, blob.Name);
                            }
                        }
                        else
                        {
                            InstallPackageIfNewer(true, workingDirectory, containerName, packageName);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(string.Format("Package \"{0}\" failed to install, {1}", package, e), "Information");
                }
            }
        }
示例#29
0
        // Below is an example of how to define a full configuration for a new storage provider that is not already specified in the config file.
        private void Example_ConfigureNewStorageProvider(ClusterConfiguration config)
        {
            const string myProviderFullTypeName = "Orleans.Storage.AzureTableStorage"; // Alternatively, can be something like typeof(AzureTableStorage).FullName
            const string myProviderName         = "MyNewAzureStoreProvider";           // what ever arbitrary name you want to give to your provider

            var    properties       = new Dictionary <string, string>();
            string connectionString = RoleEnvironment.GetConfigurationSettingValue(DATA_CONNECTION_STRING_KEY);

            properties.Add(DATA_CONNECTION_STRING_KEY, connectionString);
            properties.Add("MyCustomProperty4", "MyCustomPropertyValue4");

            config.Globals.RegisterStorageProvider(myProviderFullTypeName, myProviderName, properties);

            // Once silo starts you can see that it prints in the log:
            //  Providers:
            //      StorageProviders:
            //          Name=MyNewAzureStoreProvider, Type=Orleans.Storage.AzureTableStorage, Properties=[DataConnectionString, MyCustomProperty4]
        }
示例#30
0
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;

            //DiagnosticMonitor.Start("DiagnosticsConnectionString");

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

            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
                                                                 configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)));

            this.container = new WindsorContainer().Install(new BookingWorkerRoleWindsorInstaller());

            return(base.OnStart());
        }