public async Task <IEnumerable <VcsRepository> > GetRepositoriesAsync(VersionControlDto versionControl) { StashClient client = new StashClient(versionControl.Endpoint, versionControl.ApiKey, usePersonalAccessTokenForAuthentication: true); List <VcsRepository> results = new List <VcsRepository>(); ResponseWrapper <Project> projects = await client.Projects.Get(); foreach (Project project in projects.Values ?? Enumerable.Empty <Project>()) { ResponseWrapper <Repository> repositories = await client.Repositories.Get(project.Key, Options); foreach (Repository repository in repositories.Values ?? Enumerable.Empty <Atlassian.Stash.Entities.Repository>()) { results.Add(new VcsRepository { Id = Guid.NewGuid(), VcsId = versionControl.VcsId, WebUrl = repository.Links.Self[0].Href.ToString(), Url = repository.Links.Clone[0].Href.ToString() }); } } logger.LogInformation($"Found {results.Count} repositories for {versionControl.Endpoint}"); return(results); }
private static async void ExportRepos() { var repositories = await GetRepositories(); var tfsRepos = repositories.Where(x => x.Project.Name.Equals(TfsProjectName)); var stashClient = new StashClient(StashUrl, StashUserName, StashPassword); var projects = stashClient.Projects.Get().Result; var caeProj = projects.Values.FirstOrDefault(x => x.Name.Equals(StashProjectKey)); if (caeProj != null) { var stashRepos = await stashClient.Repositories.Get(StashProjectKey); foreach (var repository in tfsRepos) { if (stashRepos.Values.Any(x => x.Name.Equals(repository.Name, StringComparison.OrdinalIgnoreCase))) { continue; } var newRepo = new Atlassian.Stash.Entities.Repository { Name = repository.Name, Project = caeProj, Public = false }; await stashClient.Repositories.Create(StashProjectKey, newRepo); CloneRepo(repository, $"{StashUrl}/scm/{StashProjectKey.ToLowerInvariant()}/{repository.Name.ToLowerInvariant()}.git"); } } }
void ProjectToSimpleType() { const int count = 3; StashClient <KeyDataExplicit> client = GetClientWithPopulate(Guid.NewGuid(), count); var query = from x in client.CreateQuery() select new SimpleType { PKey = x.PartitionKey, RKey = x.RowKey }; int deleteCount = 0; foreach (var x in query) { client.Delete(x.PKey, x.RKey); ++deleteCount; } Assert.IsTrue(deleteCount >= count); }
GetQuery( StashClient <KeyDataWithList> stashClient, string partitionKey, string rowKey) { if (partitionKey.Is() && RowKey.Is()) { return(stashClient.CreateQuery() .Where(t => t.PartitionKey == partitionKey && t.RowKey == rowKey)); } else if (partitionKey.Is()) { return(stashClient.CreateQuery() .Where(t => t.PartitionKey == partitionKey)); } else if (rowKey.Is()) { return(stashClient.CreateQuery() .Where(t => t.RowKey == rowKey)); } else { return(stashClient.CreateQuery()); } }
void DoTestAllDataWithDictionaryMultiple() { bool isSuccess; try { StashClientOptions options = StashConfiguration.GetDefaultOptions(); AllDataWithDictionaryMultiple(options); // use large data must fail // if control came here we failed isSuccess = false; } catch (Exception) { isSuccess = true; } if (!isSuccess) { Assert.Fail(); } { StashClientOptions options = StashConfiguration.GetDefaultOptions(); options.SupportLargeObjectsInPool = true; AllDataWithDictionary entity = AllDataWithDictionaryMultiple(options); // now read without the support large pool options and validate the the entities do NOT match // and the unmapped pool count is different options.SupportLargeObjectsInPool = false; StashClient <AllDataWithDictionary> client = StashConfiguration.GetClient <AllDataWithDictionary>(options); AllDataWithDictionary entityRead = client.Get(entity.PartitionKey, entity.RowKey); Assert.IsFalse(entityRead.Equals(entity)); // now read without the support large pool options and validate the the entities DO match // and the unmapped pool count is different options.SupportLargeObjectsInPool = true; client = StashConfiguration.GetClient <AllDataWithDictionary>(options); entityRead = client.Get(entity.PartitionKey, entity.RowKey); Assert.IsTrue(entityRead.Equals(entity)); // delete client.Delete(entityRead); } }
GetQuery( StashClient <AllDataExplicit> stashClient, string pKey, string rKey) { if (pKey.Is() && rKey.Is()) { return(stashClient.CreateQuery() .Where(t => t.PartitionKey == pKey && t.RowKey == rKey)); } else if (pKey.Is()) { return(stashClient.CreateQuery() .Where(t => t.PartitionKey == pKey)); } else if (rKey.Is()) { return(stashClient.CreateQuery() .Where(t => t.RowKey == rKey)); } else { return(stashClient.CreateQuery()); } }
GetQuery( StashClient <T> stashClient, string partitionKey, string rowKey) { return((IQueryable <T>)(new T()).GetQuery( stashClient, partitionKey, rowKey)); }
public ApplicationService(IDefaultValueService defaultValueService, IAccountsService accountsService) { DefaultValueService = defaultValueService; AccountsService = accountsService; AccountsService.WhenAnyObservable(x => x.ActiveAccountChanged).StartWith(AccountsService.ActiveAccount).Subscribe(account => { StashClient = account != null ? AtlassianStashSharp.StashClient.CrateBasic(new Uri(account.Domain), account.Username, account.Password) : null; }); }
public async Task Get_TestUser_User_With_BearAuthenticationToken() { var client = new StashClient(BASE_URL, PERSONAL_ACCESS_TOKEN, true); var response = await client.Users.Get(TEST_USERNAME); var users = response.Values; Assert.IsNotNull(users); Assert.IsTrue(users.Any()); Assert.IsNotNull(users.Single(user => user.Name == TEST_USERNAME)); }
private static async void DeleteStashRepos() { var stashClient = new StashClient(StashUrl, StashUserName, StashPassword); var stashRepos = await stashClient.Repositories.Get(StashProjectKey); foreach (var repo in stashRepos.Values) { // if (repo.Name.Equals("AnalysisA3DMax")) continue; await stashClient.Repositories.Delete(StashProjectKey, repo.Slug); } }
GetClient <T>( StashClientOptions options) { // Change the type here to target different storage accounts and different credential methods. ConfigurationType configType = ConfigurationType.StashEmulator; StashClient <T> result = null; switch (configType) { // Use the StashCredential class. case ConfigurationType.StashCloud: result = new StashClient <T>( new StorageAccountKey( ConfigurationManager.AppSettings["AccountName"], ConfigurationManager.AppSettings["key"]), options); break; // The storage emulator credentials are built into Stash. case ConfigurationType.StashEmulator: result = new StashClient <T>( options); break; #if USE_STORAGE_CLIENT // Use the Azure Storage Client credentials infrastructure. case ConfigurationType.StorageAccountCloud: result = GetStasherUsingCloudStorageAccount <T>( "DataConnectionString", options); break; // Use the Azure Storage Client credentials infrastructure for the emulator. case ConfigurationType.StorageAccountEmulator: result = GetStasherUsingCloudStorageAccount <T>( "DataConnectionStringEmulator", options); break; #endif default: throw new ApplicationException("Incorrect Configuration Type."); } return(result); }
IgnoreResouceNotFoundExceptionImpl( bool ignoreResouceNotFoundException) { StashClient <KeyDataExplicit> clientWithExtra = null; KeyDataExplicit dataWritten = null; try { clientWithExtra = StashConfiguration.GetClient <KeyDataExplicit>(); clientWithExtra.CreateTableIfNotExist(); var clientMin = StashConfiguration.GetClient <KeyDataExplicit>( new StashClientOptions { IgnoreResourceNotFoundException = ignoreResouceNotFoundException, OverrideEntitySetName = instance => typeof(KeyDataExplicit).Name, OverrideEntitySetNameIsDynamic = false, }); dataWritten = new KeyDataExplicit { PartitionKey = "ResourceNotFound", RowKey = Guid.NewGuid().ToString() }; clientWithExtra.Insert(dataWritten); var dataRead = clientMin.Get( dataWritten.PartitionKey, dataWritten.RowKey + "X"); // we should reach here only if ignoreResouceNotFoundException is true Assert.IsTrue(ignoreResouceNotFoundException); Assert.IsTrue(dataRead == null); } catch (StashException stashEx) { Assert.IsTrue( !ignoreResouceNotFoundException && stashEx.Error == StashError.UnexpectedRuntime); } catch (Exception ex) { Assert.Fail(); } clientWithExtra.Delete(dataWritten); }
MissingMembersInTypeImpl( bool ignoreMissingProperties) { StashClient <MissingMembersInType> clientWithExtra = null; MissingMembersInType dataWritten = null; try { clientWithExtra = StashConfiguration.GetClient <MissingMembersInType>(); clientWithExtra.CreateTableIfNotExist(); var clientMin = StashConfiguration.GetClient <KeyDataExplicit>( new StashClientOptions { IgnoreMissingProperties = ignoreMissingProperties, OverrideEntitySetName = instance => typeof(MissingMembersInType).Name, OverrideEntitySetNameIsDynamic = false, }); dataWritten = new MissingMembersInType { PartitionKey = "MissingMember", RowKey = Guid.NewGuid().ToString(), Int0 = 0, Int1 = 1, Int2 = 2 }; clientWithExtra.Insert(dataWritten); var dataRead = clientMin.Get(dataWritten.PartitionKey, dataWritten.RowKey); // we should reach here only if ignoring missing properties Assert.IsTrue(ignoreMissingProperties); } catch (StashException stashEx) { Assert.IsTrue( !ignoreMissingProperties && stashEx.Error == StashError.MissingMembersInType); } catch (Exception ex) { Assert.Fail(); } clientWithExtra.Delete(dataWritten); }
Write <T>( StashClient <T> client, DataSize dataSize) where T : IDataHelper <T>, new() { T data = TypeFactory <T> .Create(dataSize); data = client.Insert(data); // etag not present in type or has a valid etag Assert.IsTrue(!data.HasETag() || data.GetETag().Is()); return(data); }
DoWhiteSpaceInKeys() { StashClient <WhiteSpacesInData> client = StashConfiguration.GetClient <WhiteSpacesInData>(); client.CreateTableIfNotExist(); const string partitionKey = " " + _partitionKey; // prefix string rowKey = Guid.NewGuid().ToString() + " "; // suffix const string stringField = " "; const string stringField2 = " X "; client.Insert( new WhiteSpacesInData { PartitionKey = partitionKey, RowKey = rowKey, StringField = stringField, StringField2 = stringField2 }); var data = client .CreateQuery() .Where(x => x.PartitionKey == partitionKey && x.RowKey == rowKey) .FirstOrDefault(); data = client .CreateQuery() .FirstOrDefault(x => x.PartitionKey == partitionKey && x.RowKey == rowKey); Assert.IsTrue(data != null); Assert.IsTrue(data.PartitionKey == partitionKey); Assert.IsTrue(data.RowKey == rowKey); Assert.IsTrue(data.StringField == ""); Assert.IsTrue(data.StringField2 == stringField2); client.Delete(data); }
AllDataWithDictionaryMultiple( StashClientOptions options) { StashClient <AllDataWithDictionary> client = StashConfiguration.GetClient <AllDataWithDictionary>(options); AllDataWithDictionary entity = TypeFactory <AllDataWithDictionary> .Create(DataSize.Multiple); // DataSize.Multiple client.Insert(entity); AllDataWithDictionary entityRead = client.Get(entity.PartitionKey, entity.RowKey); Assert.IsTrue(entityRead.Equals(entity)); return(entityRead); }
GetClient <T>( StashClientOptions options) { StashClient <T> result = null; switch (ConfigType) { case ConfigurationType.StashCloud: result = new StashClient <T>( new StorageAccountKey( ConfigurationManager.AppSettings["AccountName"], ConfigurationManager.AppSettings["key"]), options); break; case ConfigurationType.StashEmulator: result = new StashClient <T>( options); break; #if USE_STORAGE_CLIENT case ConfigurationType.StorageAccountCloud: result = GetStasherUsingCloudStorageAccount <T>( "DataConnectionString", options); break; case ConfigurationType.StorageAccountEmulator: result = GetStasherUsingCloudStorageAccount <T>( "DataConnectionStringEmulator", options); break; #endif } return(result); }
GetClientWithPopulate( Guid pKey, int count) { StashClient <KeyDataExplicit> client = StashConfiguration.GetClient <KeyDataExplicit>(); client.CreateTableIfNotExist(); while (count-- > 0) { client.Insert( new KeyDataExplicit { PartitionKey = pKey.ToString(), RowKey = Guid.NewGuid().ToString() }); } return(client); }
public async Task Migrate() { var client = new StashClient( _configuration.BitbucketRepoUri.ToString(), _configuration.BitbucketUsername, _configuration.BitbucketPassword); var projects = await client.Projects.Get(); var allrepositoryNames = new HashSet <string>(); foreach (var project in projects.Values) { var repositories = await client.Repositories.Get(project.Key); await MigrateProject(new MigrateProjectParameters( projectName : project.Name, description : project.Description, repositories : repositories.Values.Select(x => new Repository ( repositoryName : x.Name, cloneUrl : x.Links.Clone .Where(l => l.Name == "http") .Select(c => c.Href).First(), slug : x.Slug )).ToList() )); foreach (var repository in repositories.Values) { if (allrepositoryNames.Contains(repository.Name)) { Log.Warning("Repository {repositoryName} from project {projectName} has non unique name and it needs to be migrated manually", repository.Name, project.Name); continue; } allrepositoryNames.Add(repository.Name); } } }
public async Task <IEnumerable <Asset> > GetAssetsAsync(VersionControlDto versionControl, RepositoryDto repository) { List <Asset> results = new List <Asset>(); StashClient client = new StashClient(versionControl.Endpoint, versionControl.ApiKey, usePersonalAccessTokenForAuthentication: true); ResponseWrapper <Project> projects = await client.Projects.Get(); foreach (Project project in projects.Values ?? Enumerable.Empty <Project>()) { ResponseWrapper <Repository> repositories = await client.Repositories.Get(project.Key, Options); foreach (Repository bitBucketRepository in repositories.Values ?? Enumerable.Empty <Repository>()) { bool isRepositoryFound = bitBucketRepository.Links.Clone.Select(c => c.Href).Concat(bitBucketRepository.Links.Self.Select(s => s.Href)).Any(link => matcher.IsMatch(link.ToString(), repository.Url)); if (isRepositoryFound) { ResponseWrapper <string> filePaths = await client.Repositories.GetFiles(project.Key, bitBucketRepository.Slug, Options); foreach (string path in filePaths.Values ?? Enumerable.Empty <string>()) { if (path.IsSupported()) { File file = await client.Repositories.GetFileContents(project.Key, bitBucketRepository.Slug, path, new FileContentsOptions { Content = true, Limit = 10000 }); logger.LogInformation($"Adding '{path}' for repository {repository.RepositoryId}"); results.Add(new Asset { Id = Guid.NewGuid(), RepositoryId = repository.RepositoryId, Kind = path.GetEcosystemKind(), Path = path, Raw = string.Join(Environment.NewLine, file.FileContents) }); } } } } } return(results); }
Tutorial_08_Context() { //---------------------------------------------------------------------------------------------------------- // Create Stash Client and get a new context StashClient <Employee> client = StashConfiguration.GetClient <Employee>(); client.CreateTableIfNotExist(); StashContext <Employee> context = client.GetContext(); //---------------------------------------------------------------------------------------------------------- // Create instances of the class, place in the context and commit the changes. const int insertCount = 10; string departmentDev = Guid.NewGuid().ToString(); // create n employees and insert into the context Enumerable .Range(1, insertCount) .Select( idx => { Employee employee = new Employee { Department = departmentDev, EmployeeId = Guid.NewGuid().ToString(), Name = "John Doe", SkillLevel = 8, DateOfBirth = new DateTime(1990 - idx, 1, 1) }; // update the private field employee.SetAnnualSalary(); return(employee); }) .ToList() .ForEach( item => context.Insert(item)); // validate the the context now contains n items with the correct state. int contextInsertCount = context .GetTrackedEntities(EntityState.Inserted) .Count; Assert.IsTrue(contextInsertCount == insertCount); // commit the context // CommitStrategy.Serial, commits each insert as a single request // This is the default strategy and need not be passed in - context.Commit() would work the same context.Commit(CommitStrategy.Serial); // On a successful commit, the state of the entity changes to EntityState.Unchanged. // validate that the context contains n items with the correct state int contextUnchangedState = context .GetTrackedEntities(EntityState.Unchanged) .Count; Assert.IsTrue(contextInsertCount == contextUnchangedState); //---------------------------------------------------------------------------------------------------------- // The context continues to hold on to the entities so it is often a good idea to either clear the context // if the entities are no longer needed or better still to just create a new context. //---------------------------------------------------------------------------------------------------------- // Get a new context and query for the rows we inserted earlier by using the same partition key, // departmentDev context = client.GetContext(); context.CreateQuery().Where(emp => emp.Department == departmentDev).ToList(); // Confirm we have the corrent number of items in the context Assert.IsTrue(context.GetTrackedEntities().Count == insertCount); // Make changes to this collection of employees in the context, modifying some and deleting the others. int entityIdx = 0; int updateCount = 0; int deleteCount = 0; context .GetTrackedEntities() .ForEach( entityDescriptor => { Employee employee = entityDescriptor.Entity; if (entityIdx % 3 == 0) { context.Delete(employee); // delete every 3rd one ++deleteCount; } else // update the others { ++employee.SkillLevel; employee.SetAnnualSalary(); // change the salary of of the employee context.Update(employee); // and update in the context ++updateCount; } ++entityIdx; }); // Commit the context, this time use the Parallel strategy. // The Parallel strategy will perform all requests in parallel. In the event of an error, // a single aggregate StashAggregateException is returned containing one or more of the errors. context.Commit(CommitStrategy.Parallel); // Performing a delete will remove an entity form the context. Validate this. Assert.IsTrue(context.GetTrackedEntities().Count == insertCount - deleteCount); //---------------------------------------------------------------------------------------------------------- // Now delete all the other entities in the context context.GetTrackedEntities().ForEach( entityDescriptor => context.Delete(entityDescriptor.Entity)); // Commit the context, this time use the batch strategy. // In a nutshell, Batch is a mode supported by Azure table storage which allows, // a number and size limited request to be made. // Batch is only allowed on entities within the same Partition and has an all or none success guarantee. context.Commit(CommitStrategy.Batch); // If all were deleted successfully the context should not be tracking any entities. Assert.IsTrue(context.GetTrackedEntities().Count == 0); //---------------------------------------------------------------------------------------------------------- // So far so good. This concludes this part of the tutorial. Go Stash! }
public void Initialize() { stashClient = new StashClient(BASE_URL, USERNAME, PASSWORD); }
Tutorial_03_Explicit_Employee() { //---------------------------------------------------------------------------------------------------------- // Create the Stash Client. StashClient <Employee> client = StashConfiguration.GetClient <Employee>(); //---------------------------------------------------------------------------------------------------------- // Create the underlying table if it does not already exists client.CreateTableIfNotExist(); //---------------------------------------------------------------------------------------------------------- // Create an instance of the class const string departmentDev = "Dev"; Employee dataWritten = new Employee { Department = departmentDev, EmployeeId = Guid.NewGuid().ToString(), Name = "John Doe", SkillLevel = 8, DateOfBirth = new DateTime(1990, 1, 1) }; // update the private field dataWritten.SetAnnualSalary(); //---------------------------------------------------------------------------------------------------------- // Stash it client.Insert(dataWritten); // Note: On inserts, updates and merges, the ETag is overwritten from the ETag returned to keep the data // in sync. //---------------------------------------------------------------------------------------------------------- // And read it back Employee dataRead = client.Get(dataWritten.Department, dataWritten.EmployeeId); //---------------------------------------------------------------------------------------------------------- // Verify we got back what we put in Assert.IsTrue(dataWritten.Equals(dataRead)); // Verify that the 2 ETags are identical Assert.IsTrue(dataRead.ETagInternal == dataWritten.ETagInternal); //---------------------------------------------------------------------------------------------------------- // Change the Skill level and update the Stash dataWritten.SkillLevel += 1; dataWritten.SetAnnualSalary(); client.Update(dataWritten); //---------------------------------------------------------------------------------------------------------- // Read back the data but this time lets use LINQ Employee dataReadUpdated = client.CreateQuery() .Where(imp => imp.Department == departmentDev && imp.EmployeeId == dataWritten.EmployeeId) .FirstOrDefault(); //---------------------------------------------------------------------------------------------------------- // Again verify that we got back what we put in Assert.IsTrue(dataWritten.Equals(dataReadUpdated)); // Verify that the 2 ETags are identical Assert.IsTrue(dataWritten.ETagInternal == dataReadUpdated.ETagInternal); //---------------------------------------------------------------------------------------------------------- // now attempt to update the data read the first time around // this should fail and throw an exception since the data was updated since the row was last read and // so has a stale ETag. // Uses the implied update mode here by default. That is, if the StashETag attribute is applied to a // member in the class, implies ETag must match, bool isSuccess; try { client.Update(dataRead); isSuccess = false; } catch (Exception ex) { Assert.IsTrue((ex as StashException).Error == StashError.ETagMatchFailed); isSuccess = true; } Assert.IsTrue(isSuccess); //---------------------------------------------------------------------------------------------------------- // attempt to update it again but this time ignore ETag matching. This should succeed. // and dataRead has the latest ETag client.UpdateUnconditional(dataRead); //---------------------------------------------------------------------------------------------------------- // now attempt to delete the entity using the data written entity // this should fail and throw an exception since the data was recently updated and so has a new ETag // Uses the implied update mode here by default. That is, if the StashETag attribute is applied to a // member in the class, implies ETag must match, try { client.Delete(dataReadUpdated); isSuccess = false; } catch (Exception ex) { Assert.IsTrue((ex as StashException).Error == StashError.ETagMatchFailed); isSuccess = true; } Assert.IsTrue(isSuccess); //---------------------------------------------------------------------------------------------------------- // now delete the entity unconditionally without the need for ETag Matching. // Can instead also use client.DeleteUnconditional here too. client.Delete(dataRead, ETagMatch.Unconditional); //---------------------------------------------------------------------------------------------------------- // And verify that it was actually deleted // by attempting to read back the data var queryable = from imp in client.CreateQuery() where imp.Department == dataWritten.Department && imp.EmployeeId == dataWritten.EmployeeId select imp; Assert.IsTrue(queryable.ToList().Count == 0); //---------------------------------------------------------------------------------------------------------- // Essentially the ETag gist is this. // Define and decorate a member in your type with an ETag if you want to optimistic concurrency support. // Stash will keep you ETag in sync across inserts, updates and merges. // There are multiple ways to implicitly override ETag matching if that is what is wanted. // The implicit way to disable optimistic concurrency support is not to define an ETag member. //---------------------------------------------------------------------------------------------------------- // So far so good. This concludes this part of the tutorial. Go Stash! }
Tutorial_01_Implicit_JobApplicant() { //---------------------------------------------------------------------------------------------------------- // Create the Stash Client. // Our helper class offers various flavors of this. StashClient <JobApplicant> client = StashConfiguration.GetClient <JobApplicant>(); //---------------------------------------------------------------------------------------------------------- // Create the corresponding table or confirm that it exists // The table name can be inferred using various methods. In this case it is inferred from the class name, // 'JobApplicant'. client.CreateTableIfNotExist(); //---------------------------------------------------------------------------------------------------------- // Create an instance of the class we want to Stash JobApplicant dataWritten = new JobApplicant { PartitionKey = "A", RowKey = Guid.NewGuid().ToString(), Name = "John Doe", Skill_Level = 1 }; //---------------------------------------------------------------------------------------------------------- // Stash it client.Insert(dataWritten); //---------------------------------------------------------------------------------------------------------- // Read back the data, using the partition and row key, no need to use LINQ here. JobApplicant dataRead = client.Get(dataWritten.PartitionKey, dataWritten.RowKey); //---------------------------------------------------------------------------------------------------------- // Verify we got back what we put in Assert.IsTrue(dataWritten.Equals(dataRead)); //---------------------------------------------------------------------------------------------------------- // Lets change the SkillLevel and Update dataWritten.Skill_Level += 1; client.Update(dataWritten); //---------------------------------------------------------------------------------------------------------- // Read back the data but this time lets use LINQ dataRead = client.CreateQuery() .Where(imp => imp.PartitionKey == dataWritten.PartitionKey && imp.RowKey == dataWritten.RowKey) .FirstOrDefault(); //---------------------------------------------------------------------------------------------------------- // Again verify that we got back what we put in Assert.IsTrue(dataWritten.Equals(dataRead)); //---------------------------------------------------------------------------------------------------------- // now delete the entity client.Delete(dataWritten); //---------------------------------------------------------------------------------------------------------- // And verify that it was actually deleted // by attempting to read back the data var queryable = from imp in client.CreateQuery() where imp.PartitionKey == dataWritten.PartitionKey && imp.RowKey == dataWritten.RowKey select imp; Assert.IsTrue(queryable.ToList().Count == 0); //---------------------------------------------------------------------------------------------------------- // So far so good. This concludes this part of the tutorial. Go Stash! }
public static StashClient ConnectToBitBucket() { var client = new StashClient(_server, _user, _password); return(client); }
public BitBucketAvailableRepositoryFactory(string bitbucketServerUrl) { Client = new StashClient(bitbucketServerUrl); }
Tutorial_09_CompositeKeys() { //---------------------------------------------------------------------------------------------------------- // Create Stash Client StashClient <EmployeeCompensation> client = StashConfiguration.GetClient <EmployeeCompensation>(); client.CreateTableIfNotExist(); //---------------------------------------------------------------------------------------------------------- // Populate the table with 10 years of salary information int nbrOfYears = 10; DateTime today = DateTime.Now.ToUniversalTime(); DateTime hireDate = today.AddYears(-nbrOfYears); Guid employeeId = Guid.NewGuid(); // Insert 10 years of data, such that each year the salary goes up by 5000. for (int yr = 0; yr < nbrOfYears; ++yr) { client.Insert( new EmployeeCompensation { EmployeeId = employeeId, CompDate = new CompensationEvent { CompensationType = CompensatationTypeValue.Salary, Date = hireDate.AddYears(yr) }, Amount = 65000 + (yr * 5000) }); } //---------------------------------------------------------------------------------------------------------- // Populate the table with the last 12 months of commission information int nbrOfMths = 12; // Insert 12 months of data, such that each year the commission goes up by 50. for (int mth = 0; mth < nbrOfMths; ++mth) { client.Insert( new EmployeeCompensation { EmployeeId = employeeId, CompDate = new CompensationEvent { CompensationType = CompensatationTypeValue.Commission, Date = today.AddMonths(-mth) }, Amount = 1000 + (mth * 50) }); } //---------------------------------------------------------------------------------------------------------- // Get the last salary EmployeeCompensation employeeCompensation = client .CreateQuery() .Where(e => e.EmployeeId == employeeId && e.CompDate == new CompensationEvent { CompensationType = CompensatationTypeValue.Salary }) // no need to specify the latest date, we get the first row, which // has the latest date. .Take(1) // first row .FirstOrDefault(); // verify we got the last date and last salary amount Assert.IsTrue(employeeCompensation.CompDate.Date.Date == hireDate.Date.AddYears((nbrOfYears - 1))); Assert.IsTrue(employeeCompensation.Amount == 65000 + ((nbrOfYears - 1) * 5000)); // How does this work? // Stash converts the "Compensation Type == 'S'" into // "RowKey >= 'S' and RowKey < 'T'" and asks to only return the first one (Take(1)) // In this case the last dated event is the first row, since the date is morphed // to the number of days before an arbitrary end date, such that the morphed date is // effectively in reverse order //---------------------------------------------------------------------------------------------------------- // Get all the commissions List <EmployeeCompensation> commissions = client .CreateQuery() .Where(e => e.EmployeeId == employeeId && e.CompDate == new CompensationEvent { CompensationType = CompensatationTypeValue.Commission }) // no need to specify the date, we get all the commissions // for the employee because again the query mapped the '==' to a range '>= and <'. .ToList(); Assert.IsTrue(commissions.Count == nbrOfMths); //---------------------------------------------------------------------------------------------------------- // Get commissions for the 4 months, prior to the last 4 months commissions = client .CreateQuery() .Where(e => e.EmployeeId == employeeId && e.CompDate >= new CompensationEvent { CompensationType = CompensatationTypeValue.Commission, Date = today.AddDays(-5).AddMonths(-8) } && e.CompDate <= new CompensationEvent { CompensationType = CompensatationTypeValue.Commission, Date = today.AddDays(-5).AddMonths(-4) } ) .ToList(); Assert.IsTrue(commissions.Count == 4); // How does this work? // Stash converts the query from a '>= X && < Y' to // < X && >= Y because the morpher indicated that 'IsCollationEquivalent' was false. // otherwise this query would have returned no rows because the range is inverted. //---------------------------------------------------------------------------------------------------------- }
Tutorial_06_Collections() { //---------------------------------------------------------------------------------------------------------- // Create a Stash Client StashClient <EmployeeSkills> client = StashConfiguration.GetClient <EmployeeSkills>(); client.CreateTableIfNotExist(); //---------------------------------------------------------------------------------------------------------- // Lets create an instance of the class we what to 'stash' const string departmentDev = "Dev"; const string ssn = "123456789"; EmployeeSkills dataWritten = new EmployeeSkills { Department = departmentDev, EmployeeId = Guid.NewGuid().ToString(), Name = "John Doe", SkillLevel = 8, DateOfBirth = new DateTime(1990, 1, 1), SSN = ssn, Salutation = Salutation.Ms }; // update the private field dataWritten.SetAnnualSalary(); // Populate Languages, certification and salary history dataWritten.Languages = new List <ProgramingLanguages> { ProgramingLanguages.Assembly, ProgramingLanguages.VisualBasic }; const string cert0 = "MSSQL", cert1 = "MSCPP", cert2 = "MSRP"; dataWritten.Certifications = new ArrayList { cert0, cert1, cert2 }; dataWritten.SalaryHistory = new SalaryInfo[] { new SalaryInfo { DateStart = new DateTime(2009, 1, 1), DateEnd = new DateTime(2010, 1, 1), Salary = 100000 }, new SalaryInfo { DateStart = new DateTime(2010, 1, 1), DateEnd = new DateTime(2012, 1, 1), Salary = 110000 }, }; dataWritten.MysteryNumbers = new int[] { 3, 2, 1, 0 }; //---------------------------------------------------------------------------------------------------------- // Stash it client.Insert(dataWritten); //---------------------------------------------------------------------------------------------------------- // Read back the data EmployeeSkills dataRead = client.Get(dataWritten.Department, dataWritten.EmployeeId); //---------------------------------------------------------------------------------------------------------- // Verify we got back what we put in Assert.IsTrue(dataWritten.Equals(dataRead)); //---------------------------------------------------------------------------------------------------------- // Verify exactly what was written to table storage by using the Generic Pool class we wrote // earlier. // set this up to target the correct table storage entity set StashClient <GenericPool> clientGenericPool = StashConfiguration.GetClient <GenericPool>( new StashClientOptions { OverrideEntitySetName = o => "EmployeeSkills", OverrideEntitySetNameIsDynamic = false, Feedback = StashConfiguration.TraceFeedback, }); GenericPool dataPool = clientGenericPool.Get( dataRead.Department, dataRead.EmployeeId); // All collection items are suffixed with the index base 0, in the format "_000". // Because the "_" is used for demarcating collection indexes, explicit defined members are not allowed // to have the embedded "_" character in the table property name. // Test for languages Assert.IsTrue( dataPool.Pool.Where( kv => kv.Key == "Languages_000" && ((ProgramingLanguages)kv.Value == ProgramingLanguages.Assembly)).ToList().Count == 1); Assert.IsTrue( dataPool.Pool.Where( kv => kv.Key == "Languages_001" && ((ProgramingLanguages)kv.Value == ProgramingLanguages.VisualBasic)).ToList().Count == 1); // Test for certification Assert.IsTrue( dataPool.Pool.Where( kv => kv.Key == "Certifications_000" && ((string)kv.Value == cert0)).ToList().Count == 1); Assert.IsTrue( dataPool.Pool.Where( kv => kv.Key == "Certifications_001" && ((string)kv.Value == cert1)).ToList().Count == 1); Assert.IsTrue( dataPool.Pool.Where( kv => kv.Key == "Certifications_002" && ((string)kv.Value == cert2)).ToList().Count == 1); // Test salary history - key only Assert.IsTrue( dataPool.Pool.Where( kv => kv.Key == "SalaryHistory_000").ToList().Count == 1); Assert.IsTrue( dataPool.Pool.Where( kv => kv.Key == "SalaryHistory_001").ToList().Count == 1); // Mystery numbers ... well they were persisted using the DataContract Serializer // and persisted as XML as a single table property. Assert.IsTrue( dataPool.Pool.Where( kv => kv.Key == "MysteryNumbers").ToList().Count == 1); //---------------------------------------------------------------------------------------------------------- // now delete the entity client.Delete( departmentDev, dataWritten.EmployeeId); //---------------------------------------------------------------------------------------------------------- // And verify that it was actually deleted // by attempting to read back the data var queryable = from imp in client.CreateQuery() where imp.Department == dataWritten.Department && imp.EmployeeId == dataWritten.EmployeeId select imp; Assert.IsTrue(queryable.ToList().Count == 0); //---------------------------------------------------------------------------------------------------------- // So far so good. This concludes this part of the tutorial. Go Stash! }
Tutorial_04_DictionaryPool() { //---------------------------------------------------------------------------------------------------------- // Create a Stash Client for the Employee class StashClient <Employee> clientEmployee = StashConfiguration.GetClient <Employee>(); clientEmployee.CreateTableIfNotExist(); //---------------------------------------------------------------------------------------------------------- // Create an StashClient for the generic pool class, // Since we want to read and write to the Employee table, notice how we setup the correct EntityName in // the StashClientOptions. Otherwise the azure table implied would be "GenericPool". // // The call back method of naming the table has flexible capabilities. It can be used to determine // the table name dynamically based on the data in the object instance. // In this case it is used statically and called only once. StashClient <GenericPool> clientGenericPool = StashConfiguration.GetClient <GenericPool>( new StashClientOptions { OverrideEntitySetName = o => "Employee", OverrideEntitySetNameIsDynamic = false, Feedback = StashConfiguration.TraceFeedback, }); //---------------------------------------------------------------------------------------------------------- // Stash an Employee const string departmentDev = "Dev"; Employee dataEmployee = new Employee { Department = departmentDev, EmployeeId = Guid.NewGuid().ToString(), Name = "John Doe", SkillLevel = 8, DateOfBirth = new DateTime(1990, 1, 1) }; dataEmployee.SetAnnualSalary(); clientEmployee.Insert(dataEmployee); //---------------------------------------------------------------------------------------------------------- // and read it back thru the GenericPool GenericPool dataPool = clientGenericPool.Get( dataEmployee.Department, dataEmployee.EmployeeId); //---------------------------------------------------------------------------------------------------------- // Verify we got back what we put in via the Employee type. Assert.IsTrue( dataPool.PrimaryKey == dataEmployee.Department && dataPool.SecondaryKey == dataEmployee.EmployeeId && dataPool.Pool["AnnualSalary"].Equals(dataEmployee.GetAnnualSalary()) && dataPool.Pool["Birthday"].Equals(dataEmployee.DateOfBirth) && dataPool.Pool["SkillLevel"].Equals(dataEmployee.SkillLevel) && dataPool.Pool["Name"].Equals(dataEmployee.Name) && dataPool.Pool.Count == 4 + 1); // + 1 to the ETag //---------------------------------------------------------------------------------------------------------- // Make a few changes and update dataPool.Pool["Name"] = "Lucifure"; // name change dataPool.Pool["Unique"] = Guid.NewGuid(); // new field clientGenericPool.Update(dataPool); // Note: Updates, Merges etc keep the original objects in sync with the latest ETags. // Even if an ETag is not specified for the type, if the type supports a Pool, // the ETag is maintained and synched in the pool //---------------------------------------------------------------------------------------------------------- // Read back the data GenericPool dataPoolRead = clientGenericPool.CreateQuery() .Where(imp => imp.PrimaryKey == dataEmployee.Department && imp.SecondaryKey == dataEmployee.EmployeeId) .FirstOrDefault(); //---------------------------------------------------------------------------------------------------------- // and verify that we got back what we put in Assert.IsTrue( dataPool.PrimaryKey == dataPoolRead.PrimaryKey && dataPool.SecondaryKey == dataPoolRead.SecondaryKey && StashHelper.DictionaryEquals( dataPool.Pool, dataPoolRead.Pool)); //---------------------------------------------------------------------------------------------------------- // Merge can be performed very efficiently with a StashPool. Only include the tables properties // to be merge in the dictionary. No need to null out members or defined nullable value type members. // Create a new pool with just the objects of interest Dictionary <string, object> pool = new Dictionary <string, object>(); // save the current etag (for now and later) string etagPreMerge = dataPoolRead.Pool[Literal.ETag].ToString(); pool["Name"] = "Stash"; // new value to merge pool[Literal.ETag] = etagPreMerge; // get the ETag too // create a new pool object for merging. GenericPool dataPoolMerged = new GenericPool { PrimaryKey = dataPoolRead.PrimaryKey, SecondaryKey = dataPoolRead.SecondaryKey, Pool = pool }; clientGenericPool.Merge(dataPoolMerged, ETagMatch.Must); // force ETag matching. // read back and verify GenericPool dataPoolMergedRead = clientGenericPool.Get( dataPoolMerged.PrimaryKey, dataPoolMerged.SecondaryKey); // validate Assert.IsTrue(dataPoolMergedRead.Pool.Count == dataPoolRead.Pool.Count && dataPoolMergedRead.Pool["Name"] as String == "Stash"); //---------------------------------------------------------------------------------------------------------- // attempt to merge again, replacing the current ETag with the old one. bool isSuccess; try { // use the defunct etag to exhibit this dataPoolMerged.Pool[Literal.ETag] = etagPreMerge; clientGenericPool.Merge(dataPoolMerged); isSuccess = false; } catch (Exception ex) { // Merge fails because the ETag was old and did not match. Assert.IsTrue((ex as StashException).Error == StashError.ETagMatchFailed); isSuccess = true; } Assert.IsTrue(isSuccess); //---------------------------------------------------------------------------------------------------------- // attempt to merge yet again, this time by disabling ETag matching. clientGenericPool.Merge(dataPoolMerged, ETagMatch.Unconditional); //---------------------------------------------------------------------------------------------------------- // now attempt to delete the entity try { clientGenericPool.Delete(dataPoolMergedRead); // Implicit ETag matching, will make this fail too // because the last update changed the ETag isSuccess = false; } catch (Exception ex) { Assert.IsTrue((ex as StashException).Error == StashError.ETagMatchFailed); isSuccess = true; } Assert.IsTrue(isSuccess); //---------------------------------------------------------------------------------------------------------- // Do an unconditional delete clientGenericPool.DeleteUnconditional(dataPoolMergedRead); //---------------------------------------------------------------------------------------------------------- // And verify that it was actually deleted // by attempting to read back the data var queryable = from emp in clientEmployee.CreateQuery() where emp.Department == dataEmployee.Department && emp.EmployeeId == dataEmployee.EmployeeId select emp; Assert.IsTrue(queryable.ToList().Count == 0); //---------------------------------------------------------------------------------------------------------- // So far so good. This concludes this part of the tutorial. Go Stash! }
private StashClient getStashClient(string personalAccessKey) { var client = new StashClient("https://repo.ovotrack.nl", personalAccessKey, true); return(client); }