public WindowsAzureStorageHelper()
        {
            ContainerName = CONTAINER_NAME;
            // Open blob storage.

            StorageAccountInfo          = StorageAccountInfo.GetDefaultBlobStorageAccountFromConfiguration();
            BlobStorageType             = BlobStorage.Create(StorageAccountInfo);
            BlobStorageType.RetryPolicy = RetryPolicies.RetryN(2, TimeSpan.FromMilliseconds(100));

            // Open queue storage.

            StorageAccountInfo queueAccount = StorageAccountInfo.GetDefaultQueueStorageAccountFromConfiguration();

            QueueStorageType             = QueueStorage.Create(queueAccount);
            QueueStorageType             = QueueStorage.Create(queueAccount);
            QueueStorageType.RetryPolicy = RetryPolicies.RetryN(2, TimeSpan.FromMilliseconds(100));

            // Open table storage.

            StorageAccountInfo tableAccount = StorageAccountInfo.GetDefaultTableStorageAccountFromConfiguration();

            TableStorageType             = TableStorage.Create(tableAccount);
            TableStorageType             = TableStorage.Create(tableAccount);
            TableStorageType.RetryPolicy = RetryPolicies.RetryN(2, TimeSpan.FromMilliseconds(100));
        }
Exemplo n.º 2
0
            private static void ApplicationStartUponFirstRequest(HttpContext context)
            {
                // This is where you put initialization logic for the site.
                // RoleManager is properly initialized at this point.

                // Create the tables on first request initialization as there is a performance impact
                // if you call CreateTablesFromModel() when the tables already exist. This limits the exposure of
                // creating tables multiple times.

                // Get the settings from the Service Configuration file
                StorageAccountInfo account = StorageAccountInfo.GetDefaultTableStorageAccountFromConfiguration();

                // Create the tables
                // In this case, just a single table.
                // This will create tables for all public properties that are IQueryable (collections)
                TableStorage.CreateTablesFromModel(typeof(zlnkDC), account);
            }
Exemplo n.º 3
0
        // RoleProvider methods
        public override void Initialize(string name, NameValueCollection config)
        {
            // Verify that config isn't null
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            // Assign the provider a default name if it doesn't have one
            if (String.IsNullOrEmpty(name))
            {
                name = "TableStorageRoleProvider";
            }

            // Add a default "description" attribute to config if the
            // attribute doesn't exist or is empty
            if (string.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "Table storage-based role provider");
            }

            // Call the base class's Initialize method
            base.Initialize(name, config);

            bool allowInsecureRemoteEndpoints = Configuration.GetBooleanValue(config, "allowInsecureRemoteEndpoints", false);

            // structure storage-related properties
            ApplicationName = Configuration.GetStringValueWithGlobalDefault(config, "applicationName",
                                                                            Configuration.DefaultProviderApplicationNameConfigurationString,
                                                                            Configuration.DefaultProviderApplicationName, false);
            _accountName = Configuration.GetStringValue(config, "accountName", null, true);
            _sharedKey   = Configuration.GetStringValue(config, "sharedKey", null, true);
            _tableName   = Configuration.GetStringValueWithGlobalDefault(config, "roleTableName",
                                                                         Configuration.DefaultRoleTableNameConfigurationString,
                                                                         Configuration.DefaultRoleTableName, false);
            _membershipTableName = Configuration.GetStringValueWithGlobalDefault(config, "membershipTableName",
                                                                                 Configuration.DefaultMembershipTableNameConfigurationString,
                                                                                 Configuration.DefaultMembershipTableName, false);
            _tableServiceBaseUri = Configuration.GetStringValue(config, "tableServiceBaseUri", null, true);

            // remove required attributes
            config.Remove("allowInsecureRemoteEndpoints");
            config.Remove("applicationName");
            config.Remove("accountName");
            config.Remove("sharedKey");
            config.Remove("roleTableName");
            config.Remove("membershipTableName");
            config.Remove("tableServiceBaseUri");


            // Throw an exception if unrecognized attributes remain
            if (config.Count > 0)
            {
                string attr = config.GetKey(0);
                if (!String.IsNullOrEmpty(attr))
                {
                    throw new ProviderException(string.Format(CultureInfo.InstalledUICulture, "Unrecognized attribute: {0}", attr));
                }
            }

            StorageAccountInfo info = null;

            try
            {
                info = StorageAccountInfo.GetDefaultTableStorageAccountFromConfiguration(true);
                if (_tableServiceBaseUri != null)
                {
                    info.BaseUri = new Uri(_tableServiceBaseUri);
                }
                if (_accountName != null)
                {
                    info.AccountName = _accountName;
                }
                if (_sharedKey != null)
                {
                    info.Base64Key = _sharedKey;
                }
                info.CheckComplete();
                SecUtility.CheckAllowInsecureEndpoints(allowInsecureRemoteEndpoints, info);
                _tableStorage             = TableStorage.Create(info);
                _tableStorage.RetryPolicy = _tableRetry;
                _tableStorage.TryCreateTable(_tableName);
            }
            catch (SecurityException)
            {
                throw;
            }
            // catch InvalidOperationException as well as StorageException
            catch (Exception e)
            {
                string exceptionDescription = Configuration.GetInitExceptionDescription(info, "table storage configuration");
                string tableName            = (_tableName == null) ? "no role table name specified" : _tableName;
                Log.Write(EventKind.Error, "Could not create or find role table: " + tableName + "!" + Environment.NewLine +
                          exceptionDescription + Environment.NewLine +
                          e.Message + Environment.NewLine + e.StackTrace);
                throw new ProviderException("Could not create or find role table. The most probable reason for this is that " +
                                            "the storage endpoints are not configured correctly. Please look at the configuration settings " +
                                            "in your .cscfg and Web.config files. More information about this error " +
                                            "can be found in the logs when running inside the hosting environment or in the output " +
                                            "window of Visual Studio.", e);
            }
        }
        public override void Initialize(string name, NameValueCollection config)
        {
            // Verify that config isn't null
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            // Assign the provider a default name if it doesn't have one
            if (String.IsNullOrEmpty(name))
            {
                name = "TableServiceSessionStateProvider";
            }

            // Add a default "description" attribute to config if the
            // attribute doesn't exist or is empty
            if (string.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "Session state provider using table storage");
            }

            // Call the base class's Initialize method
            base.Initialize(name, config);

            bool allowInsecureRemoteEndpoints = Configuration.GetBooleanValue(config, "allowInsecureRemoteEndpoints", false);

            // structure storage-related properties
            _applicationName = Configuration.GetStringValueWithGlobalDefault(config, "applicationName",
                                                                             Configuration.DefaultProviderApplicationNameConfigurationString,
                                                                             Configuration.DefaultProviderApplicationName, false);
            _accountName = Configuration.GetStringValue(config, "accountName", null, true);
            _sharedKey   = Configuration.GetStringValue(config, "sharedKey", null, true);
            _tableName   = Configuration.GetStringValueWithGlobalDefault(config, "sessionTableName",
                                                                         Configuration.DefaultSessionTableNameConfigurationString,
                                                                         Configuration.DefaultSessionTableName, false);
            _tableServiceBaseUri = Configuration.GetStringValue(config, "tableServiceBaseUri", null, true);
            _containerName       = Configuration.GetStringValueWithGlobalDefault(config, "containerName",
                                                                                 Configuration.DefaultSessionContainerNameConfigurationString,
                                                                                 Configuration.DefaultSessionContainerName, false);
            if (!SecUtility.IsValidContainerName(_containerName))
            {
                throw new ProviderException("The provider configuration for the TableStorageSessionStateProvider does not contain a valid container name. " +
                                            "Please refer to the documentation for the concrete rules for valid container names." +
                                            "The current container name is: " + _containerName);
            }
            _blobServiceBaseUri = Configuration.GetStringValue(config, "blobServiceBaseUri", null, true);

            config.Remove("allowInsecureRemoteEndpoints");
            config.Remove("accountName");
            config.Remove("sharedKey");
            config.Remove("containerName");
            config.Remove("applicationName");
            config.Remove("blobServiceBaseUri");
            config.Remove("tableServiceBaseUri");
            config.Remove("sessionTableName");

            // Throw an exception if unrecognized attributes remain
            if (config.Count > 0)
            {
                string attr = config.GetKey(0);
                if (!String.IsNullOrEmpty(attr))
                {
                    throw new ProviderException
                              ("Unrecognized attribute: " + attr);
                }
            }

            StorageAccountInfo tableInfo = null;
            StorageAccountInfo blobInfo  = null;

            try
            {
                tableInfo = StorageAccountInfo.GetDefaultTableStorageAccountFromConfiguration(true);
                blobInfo  = StorageAccountInfo.GetDefaultBlobStorageAccountFromConfiguration(true);
                if (_tableServiceBaseUri != null)
                {
                    tableInfo.BaseUri = new Uri(_tableServiceBaseUri);
                }
                if (_blobServiceBaseUri != null)
                {
                    blobInfo.BaseUri = new Uri(_blobServiceBaseUri);
                }
                if (_accountName != null)
                {
                    tableInfo.AccountName = _accountName;
                    blobInfo.AccountName  = _accountName;
                }
                if (_sharedKey != null)
                {
                    tableInfo.Base64Key = _sharedKey;
                    blobInfo.Base64Key  = _sharedKey;
                }
                tableInfo.CheckComplete();
                SecUtility.CheckAllowInsecureEndpoints(allowInsecureRemoteEndpoints, tableInfo);
                blobInfo.CheckComplete();
                SecUtility.CheckAllowInsecureEndpoints(allowInsecureRemoteEndpoints, blobInfo);
                _tableStorage             = TableStorage.Create(tableInfo);
                _tableStorage.RetryPolicy = _tableRetry;
                _tableStorage.TryCreateTable(_tableName);
                _blobProvider = new BlobProvider(blobInfo, _containerName);
            }
            catch (SecurityException)
            {
                throw;
            }
            // catch InvalidOperationException as well as StorageException
            catch (Exception e)
            {
                string exceptionDescription = Configuration.GetInitExceptionDescription(tableInfo, blobInfo);
                string tableName            = (_tableName == null) ? "no session table name specified" : _tableName;
                string containerName        = (_containerName == null) ? "no container name specified" : _containerName;
                Log.Write(EventKind.Error, "Initialization of data service structures (tables and/or blobs) failed!" +
                          exceptionDescription + Environment.NewLine +
                          "Configured blob container: " + containerName + Environment.NewLine +
                          "Configured table name: " + tableName + Environment.NewLine +
                          e.Message + Environment.NewLine + e.StackTrace);
                throw new ProviderException("Initialization of data service structures (tables and/or blobs) failed!" +
                                            "The most probable reason for this is that " +
                                            "the storage endpoints are not configured correctly. Please look at the configuration settings " +
                                            "in your .cscfg and Web.config files. More information about this error " +
                                            "can be found in the logs when running inside the hosting environment or in the output " +
                                            "window of Visual Studio.", e);
            }
            Debug.Assert(_blobProvider != null);
        }
Exemplo n.º 5
0
 public zlnkDC() :
     base(StorageAccountInfo.GetDefaultTableStorageAccountFromConfiguration())
 {
 }
Exemplo n.º 6
0
        // shows alternative ways of generating DataServiceContext objects
        internal static void RunSamples2()
        {
            StorageAccountInfo account = null;

            try
            {
                account = StorageAccountInfo.GetDefaultTableStorageAccountFromConfiguration();
                TableStorage tableStorage = TableStorage.Create(account);
                tableStorage.RetryPolicy = RetryPolicies.RetryN(3, TimeSpan.FromSeconds(1));
                // the DataServiceContext object inherits its retry policy from tableStorage in this case
                TableStorageDataServiceContext svc = tableStorage.GetDataServiceContext();


                Console.WriteLine("Table creation, delete and list samples...");
                string sampleTableName = SampleDataServiceContext.SampleTableName;
                tableStorage.TryCreateTable(sampleTableName);

                DeleteAllEntriesFromSampleTable(svc, sampleTableName);

                Console.WriteLine("List all tables in the account.");
                IEnumerable <string> tables2 = tableStorage.ListTables();
                foreach (string n1 in tables2)
                {
                    Console.WriteLine(n1);
                }

                Console.WriteLine("Inserting entities into the table...");

                SampleEntity t = new SampleEntity("samplepartitionkey", "samplerowkey");
                svc.AddObject(sampleTableName, t);
                svc.SaveChangesWithRetries();

                //Detach the existing entity so that we can demonstrate the server side
                //error when you try to insert an same object with the same keys
                svc.Detach(t);

                // Insert an entity with the same keys
                Console.WriteLine("Try to insert the same entity into the table and show how to deal with error conditions.");

                t = new SampleEntity("samplepartitionkey", "samplerowkey");
                svc.AddObject(sampleTableName, t);
                try
                {
                    svc.SaveChangesWithRetries();
                    // getting here is an error because inserting the same row twice raises an exception
                    Console.WriteLine("Should not get here. Succeeded inserting two entities with the same keys");
                }
                catch (Exception e)
                {
                    HttpStatusCode status;
                    StorageExtendedErrorInformation errorInfo;
                    if (TableStorageHelpers.EvaluateException(e, out status, out errorInfo) &&
                        status == HttpStatusCode.Conflict)
                    {
                        // the row has already been inserted before, this is expected here
                        if (errorInfo != null)
                        {
                            Console.WriteLine("Attempting to insert row with same keys resulted in error {0} : {1}",
                                              errorInfo.ErrorCode, errorInfo.ErrorMessage);
                        }
                    }
                    else
                    {
                        throw;
                    }
                }

                svc.Detach(t);

                Console.WriteLine("Insert a large item into the table.");
                t   = new SampleEntity("samplepartitionkey", "samplerowkey1");
                t.B = new String('a', 1000);
                svc.AddObject(sampleTableName, t);
                svc.SaveChangesWithRetries();

                Console.WriteLine("Create a normal DataServiceContext object (not TableStorageDataServiceContext) and attach it to a TableStorage object.");
                DataServiceContext svc2 = new DataServiceContext(
                    TableStorage.GetServiceBaseUri(account.BaseUri, account.UsePathStyleUris, account.AccountName));
                tableStorage.Attach(svc2);

                var qResult = from c in svc2.CreateQuery <SampleEntity>(sampleTableName)
                              where c.RowKey == "samplerowkey1"
                              select c;

                foreach (SampleEntity cust in qResult)
                {
                    if (cust.B != t.B)
                    {
                        Console.WriteLine("Sample failed. Did not read the entity property just written");
                    }
                }

                Console.WriteLine("Insert many rows in a table and show the API for dealing with query result pagination.");

                int num = 2100;
                Console.WriteLine("Inserting {0} rows.", num.ToString(CultureInfo.CurrentUICulture));
                for (int i = 0; i < num; i++)
                {
                    t = new SampleEntity("samplestring", i.ToString(CultureInfo.InvariantCulture));
                    svc.AddObject(sampleTableName, t);
                    svc.SaveChangesWithRetries();
                    if ((i + 1) % 50 == 0)
                    {
                        Console.WriteLine("Inserted row {0}.", (i + 1).ToString(CultureInfo.CurrentUICulture));
                    }
                }

                Console.WriteLine("Executing query that will return many results. This can take a while...");
                var qResult2 = from c in svc.CreateQuery <SampleEntity>(sampleTableName)
                               where c.PartitionKey == "samplestring"
                               select c;

                TableStorageDataServiceQuery <SampleEntity> tableStorageQuery = new TableStorageDataServiceQuery <SampleEntity>(qResult2 as DataServiceQuery <SampleEntity>);
                IEnumerable <SampleEntity> res = tableStorageQuery.ExecuteAllWithRetries();
                Console.WriteLine("Retrieved query results:");
                foreach (SampleEntity entity in res)
                {
                    Console.WriteLine("Partition key: {0}, row key: {1}.", entity.PartitionKey, entity.RowKey);
                }

                Console.WriteLine("Delete all entries in the sample table.");
                DeleteAllEntriesFromSampleTable(tableStorage.GetDataServiceContext(), sampleTableName);
                tableStorage.DeleteTable(sampleTableName);
                Console.WriteLine("Table samples finished!");
            }
            catch (DataServiceRequestException dsre)
            {
                Console.WriteLine("DataServiceRequestException: " + GetExceptionMessage(dsre));
                ShowTableStorageErrorMessage(account.BaseUri.ToString());
            }
            catch (InvalidOperationException ioe)
            {
                Console.WriteLine("Storage service error: " + GetExceptionMessage(ioe));
                ShowTableStorageErrorMessage(account.BaseUri.ToString());
            }
        }
Exemplo n.º 7
0
        // this method shows an alternative way of accessing/creating DataServiceContext objects
        // this approach is closer to what tools generate for normal ADO.NET Data Services projects
        internal static void RunSamples1()
        {
            StorageAccountInfo account = null;

            try
            {
                Console.WriteLine("Show how to create tables and queries using the SampleDataServiceContext class...");

                account = StorageAccountInfo.GetDefaultTableStorageAccountFromConfiguration();
                SampleDataServiceContext svc = new SampleDataServiceContext(account);
                svc.RetryPolicy = RetryPolicies.RetryN(3, TimeSpan.FromSeconds(1));

                // Create 'SampleTable'
                // this uses the SampleDataServiceContext class
                TableStorage.CreateTablesFromModel(typeof(SampleDataServiceContext), account);

                string sampleTableName = SampleDataServiceContext.SampleTableName;

                DeleteAllEntriesFromSampleTable(svc, sampleTableName);


                svc.AddObject(SampleDataServiceContext.SampleTableName, new SampleEntity("sample", "entity"));
                svc.SaveChangesWithRetries();

                var qResult = from c in svc.SampleTable
                              where c.PartitionKey == "samplepartitionkey" && c.RowKey == "samplerowkey1"
                              select c;

                TableStorageDataServiceQuery <SampleEntity> q = new TableStorageDataServiceQuery <SampleEntity>(qResult as DataServiceQuery <SampleEntity>, svc.RetryPolicy);

                try {
                    // the query references the whole key and explicitly addresses one entity
                    // thus, this query can generate an exception if there are 0 results during enumeration
                    IEnumerable <SampleEntity> res = q.ExecuteAllWithRetries();
                    foreach (SampleEntity s in res)
                    {
                        Console.WriteLine("This code is not reached. " + s.PartitionKey);
                    }
                } catch (DataServiceQueryException e) {
                    HttpStatusCode s;
                    if (TableStorageHelpers.EvaluateException(e, out s) && s == HttpStatusCode.NotFound)
                    {
                        // this would mean the entity was not found
                        Console.WriteLine("The entity was not found. This is expected here.");
                    }
                }

                Console.WriteLine("Delete all entries in the sample table.");
                DeleteAllEntriesFromSampleTable(svc, sampleTableName);
                Console.WriteLine("Table sample 1 finished!");
            }
            catch (DataServiceRequestException dsre)
            {
                Console.WriteLine("DataServiceRequestException: " + GetExceptionMessage(dsre));
                ShowTableStorageErrorMessage(account.BaseUri.ToString());
            }
            catch (InvalidOperationException ioe)
            {
                Console.WriteLine("Storage service error: " + GetExceptionMessage(ioe));
                ShowTableStorageErrorMessage(account.BaseUri.ToString());
            }
        }