public GitBackupStatus InPlaceGitBackup(string repositoryFolder) { var isValidGitRepository = Repository.IsValid(repositoryFolder); var createdRepository = false; if (!isValidGitRepository) { _logger.InfoFormat("Initializing git repository in folder '{0}'...", repositoryFolder); repositoryFolder = Repository.Init(repositoryFolder, false); createdRepository = true; } var numberOfFilesAdded = 0; var numberOfFilesChanged = 0; var numberOfFilesRemoved = 0; using (var repository = new Repository(repositoryFolder)) { var options = new StatusOptions(); var status = repository.RetrieveStatus(options); _logger.Debug("Repository Status: " + JsonConvert.SerializeObject(status)); if (status.IsDirty) { var untractedFiles = status.Untracked; foreach (var untrackedFile in untractedFiles) { _logger.Info("Added: " + untrackedFile.FilePath); var stageOptions = new StageOptions(); repository.Stage(untrackedFile.FilePath, stageOptions); numberOfFilesAdded++; } var modifiedFiles = status.Modified; foreach (var modifiedFile in modifiedFiles) { _logger.Info("Modified: " + modifiedFile.FilePath); var stageOptions = new StageOptions(); repository.Stage(modifiedFile.FilePath, stageOptions); numberOfFilesChanged++; } var removedFiles = status.Missing; foreach (var removedFile in removedFiles) { _logger.Info("Removed: " + removedFile.FilePath); var stageOptions = new StageOptions(); repository.Stage(removedFile.FilePath, stageOptions); numberOfFilesRemoved++; } var email = GetNoReplyEmail(); var author = new Signature(Environment.UserName, email, DateTimeOffset.Now); var committer = new Signature(Environment.UserName, email, DateTimeOffset.Now); var commitOptions = new CommitOptions(); _logger.Info("Commiting..."); repository.Commit(DateTime.Now.ToString(CultureInfo.InvariantCulture), author, committer, commitOptions); } } var gitBackupStatus = new GitBackupStatus(createdRepository, numberOfFilesAdded, numberOfFilesChanged, numberOfFilesRemoved); return(gitBackupStatus); }
protected override void OnExectute(DoWorkEventArgs e) { ReportProgress(0, VBAGitUI.ProgressInfo_Commit); var commitInfo = e.Argument as CommitInfo; var options = new CommitOptions(); options.AllowEmptyCommit = true; if (commitInfo.Files?.Count() > 0) { options.AllowEmptyCommit = false; Provider.Stage(commitInfo.Files); } if (commitInfo.Branch != "master" && commitInfo.Branch != this.CurrentBranch) { ReportProgress(50, VBAGitUI.ProgressInfo_CreateBranch); Provider.CreateBranch(commitInfo.Branch); } ReportProgress(60, VBAGitUI.ProgressInfo_Commit); Provider.Commit(commitInfo.Message, commitInfo.Author, commitInfo.When, options); }
public ActionResult UpdateCategory(Guid pk, Guid physicalInstanceId, string agency, string name, string value) { try { var client = RepositoryHelper.GetClient(); var category = client.GetLatestItem(pk, agency) as Category; CategoryMapper.UpdateCategoryProperty(category, name, value); category.Version++; var commitOptions = new CommitOptions(); commitOptions.NamedOptions.Add("RegisterOrReplace"); client.RegisterItem(category, commitOptions); using (var db = ApplicationDbContext.Create()) { var file = db.Files.Where(x => x.Id == physicalInstanceId) .FirstOrDefault(); if (file != null) { file.HasPendingMetadataUpdates = true; db.SaveChanges(); } } // For x-editable, just a simple 200 return is sufficient if things went well. return(Content(string.Empty)); } catch (Exception ex) { throw new HttpException(500, ex.Message); } }
public IList <int> Delete(IEnumerable <string> idList) { IList <int> list = new List <int>(); IList <int> result; if (idList == null && idList.Count <string>() == 0) { result = list; } else { CommitOptions value = default(CommitOptions); ResponseHeader responseHeader = this.Update(new UpdateOptions { DelById = idList.ToList <string>(), CommitOptions = new CommitOptions?(value) }); if (responseHeader != null) { list.Add(responseHeader.Status); list.Add(responseHeader.QTime); ConsoleHelper.WriteLine(string.Concat(new object[] { "删除Solr:", this.SolrServerUrl, "成功,状态:", responseHeader.Status, "执行时间:", responseHeader.QTime }), ConsoleColor.Yellow, ""); } result = list; } return(result); }
public void GetItemMakeChangeAndReregister() { VersionableBase.DefaultAgencyId = "int.example"; var client = GetClient(); // Get a ConceptScheme from the repository, // and populate the member concepts. // Note that you probably have to change the UUID here // to represent one that is in your repository. var scheme = client.GetItem( new Guid("0cc13be5-3c89-4d1a-927f-ac7634d0c05a"), "int.example", 1, ChildReferenceProcessing.Populate) as ConceptScheme; // Just add a description to the ConceptScheme. scheme.Description.Current = "This is a description we are adding."; // Before we register the new version of the item, we have to // update the version number. scheme.Version++; // Register the item with the repository. var options = new CommitOptions(); client.RegisterItem(scheme, options); }
/// <summary> /// Commit a transaction. This object must be in a transaction. /// </summary> /// <param name="options"> /// Transaction commit options. /// </param> public override void Commit(CommitOptions options) { this.CheckNotDisposed(); if (!this.inTransaction) { throw new InvalidOperationException("Not in a transaction"); } if (null != this.subTransaction) { this.Tracer.TraceWarning("committing subtransaction"); // subTransaction.Commit() raises the Committed event which will // call UnregisterSubTransaction. this.subTransaction.Commit(); } if (null != this.Committed) { this.Committed(); } CommitTransactionGrbit grbit = Transaction.GrbitFromOptions(options); Api.JetCommitTransaction(this.session, grbit); // Even if this transaction commits the work done in the transaction will // be undone if the outer transaction is rolled back. To make sure that the // correct events are sent we transfer our rollback delegates to the outer // transaction. this.TransferRollbackDelegatesToOuterTransaction(); this.inTransaction = false; this.Tracer.TraceVerbose("commit ({0})", grbit); }
public GitActionResult <string> Commit(string message, bool amend = false, bool signoff = false) { var result = new GitActionResult <string>(); using (var repository = GetRepository()) { if (string.IsNullOrEmpty(message)) { result.Succeeded = false; result.ErrorMessage = "Commit message must not be null or empty!"; //throw new ArgumentException("Commit message must not be null or empty!", "message"); } else { Signature author = repository.Config.BuildSignature(DateTimeOffset.Now); Signature committer = author; CommitOptions opts = new CommitOptions(); opts.AmendPreviousCommit = amend; var commit = repository.Commit(message, author, committer, opts); result.Succeeded = true; result.Item = commit.Sha; } return(result); } }
/// <summary> /// Commits all changes /// </summary> /// <param name="solutionFileInfo">solution file info</param> /// <param name="solutionFilePath">release solution list file</param> public void CommitAllChanges(SolutionFileInfo solutionFileInfo, string solutionFilePath) { try { Singleton.SolutionFileInfoInstance.WebJobsLog.AppendLine(" Committing Powershell Scripts" + "<br>"); string multilpleSolutionsImportPSPath = AzureFunction.BinPath + Singleton.CrmConstantsInstance.MultilpleSolutionsImport; string multilpleSolutionsImportPSPathVirtual = this.localFolder.FullName + Singleton.CrmConstantsInstance.MultilpleSolutionsImport; File.Copy(multilpleSolutionsImportPSPath, multilpleSolutionsImportPSPathVirtual, true); string solutionToBeImportedPSPath = AzureFunction.BinPath + Singleton.CrmConstantsInstance.SolutionToBeImported; string solutionToBeImportedPSPathVirtual = this.localFolder + Singleton.CrmConstantsInstance.SolutionToBeImported; File.Copy(solutionToBeImportedPSPath, solutionToBeImportedPSPathVirtual, true); Singleton.SolutionFileInfoInstance.WebJobsLog.AppendLine(" Committing solutions" + "<br>"); string fileUnmanaged = this.solutionlocalFolder + solutionFileInfo.SolutionUniqueName + "_.zip"; File.Copy(solutionFileInfo.SolutionFilePath, fileUnmanaged, true); string fileManaged = this.solutionlocalFolder + solutionFileInfo.SolutionUniqueName + "_managed_.zip"; File.Copy(solutionFileInfo.SolutionFilePathManaged, fileManaged, true); string webResources = solutionFileInfo.SolutionExtractionPath + "\\WebResources"; using (var repo = new Repository(this.localFolder.FullName)) { this.AddRepositoryIndexes(fileUnmanaged, repo); this.AddRepositoryIndexes(fileManaged, repo); this.AddWebResourcesToRepository(webResources, repo); //// todo: add extracted solution files to repository this.AddExtractedSolutionToRepository(solutionFileInfo, repo); repo.Index.Add(solutionFilePath.Replace(this.localFolder.FullName, string.Empty)); repo.Index.Add(multilpleSolutionsImportPSPathVirtual.Replace(this.localFolder.FullName, string.Empty)); repo.Index.Add(solutionToBeImportedPSPathVirtual.Replace(this.localFolder.FullName, string.Empty)); var offset = DateTimeOffset.Now; Signature author = new Signature(this.authorName, this.authorEmail, offset); Signature committer = new Signature(this.committerName, this.committerEmail, offset); CommitOptions commitOptions = new CommitOptions { AllowEmptyCommit = false }; var commit = repo.Commit(solutionFileInfo.Message, author, committer); string commitIds = solutionFileInfo.Solution.GetAttributeValue <string>(Constants.SourceControlQueueAttributeNameForCommitIds); if (string.IsNullOrEmpty(commitIds)) { commitIds = string.Empty; } commitIds += string.Format("Commit Info <br/><a href='{0}/commit/{1}'>{2}</a>", this.repoUrl, commit.Id.Sha, commit.Message); solutionFileInfo.Solution[Constants.SourceControlQueueAttributeNameForCommitIds] = commitIds; } } catch (EmptyCommitException ex) { Singleton.SolutionFileInfoInstance.WebJobsLog.AppendLine(" " + ex.Message + "<br>"); } }
/// <summary> /// Create a QualityStatement from scratch, and add it to a Repository. /// </summary> public QualityStatement CreateAndRegisterQualityStatement() { // Create the QualityStatement object and give it a label. QualityStatement statement = new QualityStatement(); statement.Label.Current = "Sample Quality Statement"; // A QualityStatement is made up of QualityStatementItems. // QualityStatementItems have two important pieces of information: // a defining Concept, and some content. // The defining Concept specifies the type of information recorded // by the item. For example, "Contact organization". // The content is the actual information, like "Statistics Denmark". // First, let's create the Concepts. Concept concept1 = new Concept(); concept1.Label.Current = "Contact organization"; Concept concept2 = new Concept(); concept2.Label.Current = "Statistical Unit"; Concept concept3 = new Concept(); concept3.Label.Current = "Statitistical Population"; // Now let's create the QualityStatementItems, and assign the appropriate // Concepts and some information. QualityStatementItem item1 = new QualityStatementItem(); item1.ComplianceConcept = concept1; item1.ComplianceDescription.Current = "Statistics Denmark"; QualityStatementItem item2 = new QualityStatementItem(); item2.ComplianceConcept = concept2; item2.ComplianceDescription.Current = "Person"; QualityStatementItem item3 = new QualityStatementItem(); item3.ComplianceConcept = concept3; item3.ComplianceDescription.Current = "Denmark"; // Add each of the items to the QualityStatement. statement.Items.Add(item1); statement.Items.Add(item2); statement.Items.Add(item3); // Add the QualityStatement and the Concepts to the Repository. var client = RepositoryIntro.GetClient(); CommitOptions options = new CommitOptions(); client.RegisterItem(statement, options); client.RegisterItem(concept1, options); client.RegisterItem(concept2, options); client.RegisterItem(concept3, options); // Also, write an XML file just so we can see how things look. string fileName = @"statement.xml"; DDIWorkflowSerializer serializer = new DDIWorkflowSerializer(); serializer.SerializeFragments(fileName, statement); return statement; }
/// <summary> /// Perform an operation inside of a transaction. The transaction is committed /// if the operation completes normally. /// </summary> /// <param name="block">The operation to perform.</param> /// <param name="options">Commit option for the transaction.</param> /// <returns>The Connection that performed the transaction.</returns> private Connection UsingTransaction(Action block, CommitOptions options) { using (var trx = this.BeginTransaction()) { block(); trx.Commit(options); } return(this); }
private void CommitLogs() { using (Repository repo = new Repository(Paths.GetEkstaziInformationFolderPath(Paths.Direction.Output))) { CommitOptions co = new CommitOptions(); Commands.Stage(repo, "*"); Signature mySignature = new Signature("Marko Vasic", "*****@*****.**", DateTimeOffset.Now); repo.Commit(GetSHA(currentCommitIndex), mySignature, mySignature); } }
public IList <int> Update(DataTable objUpdateTable) { IList <int> list = new List <int>(); List <SolrInputDocument> list2 = new List <SolrInputDocument>(); foreach (DataRow dataRow in objUpdateTable.Rows) { SolrInputDocument solrInputDocument = new SolrInputDocument(); foreach (DataColumn dataColumn in objUpdateTable.Columns) { if (dataRow[dataColumn.ColumnName] != DBNull.Value) { solrInputDocument.Add(dataColumn.ColumnName, new SolrInputField(dataColumn.ColumnName, this.GetConvertValue(dataColumn.DataType, dataRow[dataColumn.ColumnName]))); } else { solrInputDocument.Add(dataColumn.ColumnName, new SolrInputField(dataColumn.ColumnName, this.GetDefaultValue(dataColumn.DataType))); } } list2.Add(solrInputDocument); } IList <int> result; if (list2.Count <= 0) { result = list; } else { CommitOptions value = default(CommitOptions); IObjectSerializer <SolrInputDocument> objectSerializer = new ObjectSerializerTable(); ResponseHeader responseHeader = this.Update(new UpdateOptions { Docs = objectSerializer.Serialize(list2), CommitOptions = new CommitOptions?(value) }); if (responseHeader != null) { list.Add(responseHeader.Status); list.Add(responseHeader.QTime); ConsoleHelper.WriteLine(string.Concat(new object[] { "更新Solr:", this.SolrServerUrl, "成功,状态:", responseHeader.Status, "执行时间:", responseHeader.QTime }), ConsoleColor.Yellow, ""); } result = list; } return(result); }
/// <summary> /// Maps Variables to Questions where the name of the Variable matches the name of /// the Question. /// </summary> /// <param name="variableSchemeId"></param> /// <param name="questionSchemeId"></param> /// <param name="onlyTest"></param> static void MapVariablesToQuestionsAuto(IdentifierTriple variableSchemeId, IdentifierTriple questionSchemeId, bool onlyTest) { var client = RepositoryIntro.GetClient(); CommitOptions commitOptions = new CommitOptions(); VariableScheme vs = client.GetItem(variableSchemeId, ChildReferenceProcessing.Populate) as VariableScheme; QuestionScheme qs = client.GetItem(questionSchemeId, ChildReferenceProcessing.Populate) as QuestionScheme; // Grab all variable names and question names. var variableNameList = vs.Variables.Select(v => v.ItemName.Current.Substring(2)).ToList(); var questionNameList = qs.Questions.Select(q => q.ItemName.Current).ToList(); int matches = 0; foreach (string varName in variableNameList) { string foundQuestionName = questionNameList.Where(q => string.Compare(q, varName, true) == 0).FirstOrDefault(); if (foundQuestionName != null) { // If there is a question with the same name as this variable, // grab the Question and Variable objects, and assign the question // as a SourceQuestion. Variable variable = vs.Variables.SingleOrDefault(v => v.ItemName.Current == varName); Question question = qs.Questions.SingleOrDefault(q => q.ItemName.Current == foundQuestionName); if (variable != null && question != null) { variable.SourceQuestions.Add(question); variable.Version++; Console.WriteLine(string.Format("Assigning {0} to {1}", question.ItemName.Current, variable.ItemName.Current)); if (!onlyTest) { client.RegisterItem(variable, commitOptions); } matches++; } else { Console.WriteLine(string.Format("No match for {0} or {1}", varName, foundQuestionName)); } } } vs.Version++; if (!onlyTest) { client.RegisterItem(vs, commitOptions); } Console.WriteLine("Done. Found " + matches.ToString() + " matches."); }
public ResponseHeader Optimize(CommitOptions options) { options = options ?? new CommitOptions(); var cmd = new OptimizeCommand { WaitFlush = options.WaitFlush, WaitSearcher = options.WaitSearcher, ExpungeDeletes = options.ExpungeDeletes, MaxSegments = options.MaxSegments, }; return(SendAndParseHeader(cmd)); }
/// <summary> /// Commits all changes. /// </summary> /// <param name="message">The message.</param> /// <exception cref="System.Exception"></exception> public void CommitAllChanges(string message, string file, string solutionFilePath) { try { Console.WriteLine("Committing solutions"); using (var repo = new Repository(_localFolder.FullName)) { if (string.IsNullOrEmpty(file)) { //var files = _localFolder.GetFiles("*.zip", SearchOption.AllDirectories).Select(f => f.FullName); var files = _localFolder.GetFiles("*.zip").Select(f => f.FullName); //string message = commitMessage + " "; { foreach (var f in files) { if (string.IsNullOrEmpty(file)) { //message += k + ","; repo.Index.Add(f.Replace(_localFolder.FullName, string.Empty)); } else { if (f.EndsWith(file)) { repo.Index.Add(f.Replace(_localFolder.FullName, string.Empty)); } } } } } else { repo.Index.Add(file.Replace(_localFolder.FullName, string.Empty)); } repo.Index.Add(solutionFilePath.Replace(_localFolder.FullName, string.Empty)); var offset = DateTimeOffset.Now; Signature author = new Signature(_authorName, _authorEmail, offset); Signature committer = new Signature(_committerName, _committerEmail, offset); CommitOptions commitOptions = new CommitOptions(); commitOptions.AllowEmptyCommit = false; repo.Commit(message, author, committer); } } catch (EmptyCommitException ex) { Console.WriteLine(ex); } }
private static OptimizeCommand GetOptimizeCommand(CommitOptions options) { options = options ?? new CommitOptions(); var cmd = new OptimizeCommand { WaitFlush = options.WaitFlush, WaitSearcher = options.WaitSearcher, ExpungeDeletes = options.ExpungeDeletes, MaxSegments = options.MaxSegments, }; return(cmd); }
public void IngestIntoRepository(Group group) { // Register every DDI item in the repository. var client = new LocalRepositoryClient(); var options = new CommitOptions(); var gatherer = new DirtyItemGatherer(true); group.Accept(gatherer); options.NamedOptions.Add("RegisterOrReplace"); client.RegisterItems(gatherer.DirtyItems, options); }
public async Task <ResponseHeader> Commit(CommitOptions options) { options = options ?? new CommitOptions(); var cmd = new CommitCommand { WaitFlush = options.WaitFlush, WaitSearcher = options.WaitSearcher, ExpungeDeletes = options.ExpungeDeletes, MaxSegments = options.MaxSegments, }; return(await SendAndParseHeader(cmd)); }
public void GetItemChangeChildAndReregister() { VersionableBase.DefaultAgencyId = "int.example"; var client = GetClient(); // Get a ConceptScheme from the repository, // and populate the member concepts. // Note that you probably have to change the UUID here // to represent one that is in your repository. var scheme = client.GetItem( new Guid("0cc13be5-3c89-4d1a-927f-ac7634d0c05a"), "int.example", 2, ChildReferenceProcessing.Populate) as ConceptScheme; if (scheme == null || scheme.Concepts.Count < 3) { Console.WriteLine("No scheme, or not enough items in the scheme."); return; } // Grab the second concept and add a description to it. var concept = scheme.Concepts[2]; concept.Description.Current = "This is the fourth concept"; // When we change a property on the Concept, the concept's // IsDirty property is automatically set to true, indicating // that it has unsaved changes. Console.WriteLine("IsDirty: ", concept.IsDirty); // The DirtyItemGatherer will walk a set of objects and create // a list of all objects that are dirty. DirtyItemGatherer gatherer = new DirtyItemGatherer( gatherEvenIfNotDirty: false, markParentsDirty: true); scheme.Accept(gatherer); var options = new CommitOptions(); // For every changed item, increase the version and // register the new version with the repository. foreach (var item in gatherer.DirtyItems) { item.Version++; client.RegisterItem(item, options); } }
/// <summary> /// Update versions and references to a Variable along this path: /// PhysicalInstance /// DataRelationship /// Variable /// VariableStatistic /// Variable /// </summary> /// <param name="variable"></param> public static void UpdateVersionsAndSave(Variable variable, PhysicalInstance physicalInstance, DataRelationship dataRelationship, VariableStatistic variableStatistic) { var client = RepositoryHelper.GetClient(); var now = DateTime.UtcNow; var itemsToRegister = new List <IVersionable>(); itemsToRegister.Add(variable); itemsToRegister.Add(physicalInstance); itemsToRegister.Add(dataRelationship); // Increase version of the variable. variable.Version++; variable.VersionDate = now; // Increase the version and reference of the PhysicalInstance that // references the DataRelationship and VariableStatistic. physicalInstance.Version++; physicalInstance.VersionDate = now; // Increase the version and reference of the DataRelationship that references the variable. dataRelationship.Version++; dataRelationship.VersionDate = now; // Update the reference to the variable. var variableInDataRelationship = dataRelationship.LogicalRecords .SelectMany(x => x.VariablesInRecord) .Where(x => x.Identifier == variable.Identifier) .FirstOrDefault(); variableInDataRelationship.Version = variable.Version; variableInDataRelationship.VersionDate = now; // Increase the version and reference of hte VariableStatistic that references the Variable. if (variableStatistic != null) { variableStatistic.Version++; variableStatistic.VersionDate = now; variableStatistic.VariableReference.Version = variable.Version; itemsToRegister.Add(variableStatistic); } // Register all the changes. var options = new CommitOptions(); options.NamedOptions.Add("RegisterOrReplace"); client.RegisterItems(itemsToRegister, options); }
public string Commit(string message, bool amend = false, bool signoff = false) { using (var repository = GetRepository()) { if (string.IsNullOrEmpty(message)) { throw new ArgumentException("Commit message must not be null or empty!", "message"); } Signature author = repository.Config.BuildSignature(DateTimeOffset.Now); Signature committer = author; CommitOptions opts = new CommitOptions(); opts.AmendPreviousCommit = amend; var commit = repository.Commit(message, author, committer); return(commit.Sha); } }
private static void CreateDummyCommit(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var message = $"DUMMY INSERTION FOR {Options.InsertionName}"; var options = new CommitOptions() { AllowEmptyCommit = true }; var watch = Stopwatch.StartNew(); var commit = Enlistment.Commit( message, InsertionToolSignature, InsertionToolSignature, options); Log.Trace($"Committing took {watch.Elapsed.TotalSeconds} seconds"); }
private static void RegisterPullSubcommand(CommandLineApplication packagesCmd, ReportsFactory reportsFactory) { packagesCmd.Command("pull", c => { c.Description = "Incremental copy of files from remote location to local packages"; var argRemote = c.Argument("[remote]", "Path to remote packages folder"); var argSource = c.Argument("[source]", "Path to source packages folder, default is current directory"); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { c.ShowRootCommandFullNameAndVersion(); var reports = reportsFactory.CreateReports(quiet: false); bool success; if (Directory.Exists(argSource.Value)) { // Implicitly commit changes before pull var commitOptions = new CommitOptions { Reports = reports, SourcePackages = argSource.Value }; var commitCommand = new CommitCommand(commitOptions); success = commitCommand.Execute(); if (!success) { return(1); } } var pullOptions = new PullOptions { Reports = reports, SourcePackages = argSource.Value, RemotePackages = argRemote.Value }; var pullCommand = new PullCommand(pullOptions); success = pullCommand.Execute(); return(success ? 0 : 1); }); }); }
static void CreateCodeList(Variable variable, PhysicalInstance physicalInstance, DataRelationship dataRelationship, VariableStatistic variableStatistic) { // Create and save a code list with all the unique values. var codeList = CreateCodeList(physicalInstance, dataRelationship, variable, variableStatistic); variable.CodeRepresentation.Codes = codeList; if (codeList != null) { var gatherer = new ItemGathererVisitor(); codeList.Accept(gatherer); var client = RepositoryHelper.GetClient(); var repoOptions = new CommitOptions(); repoOptions.NamedOptions.Add("RegisterOrReplace"); client.RegisterItems(gatherer.FoundItems, repoOptions); } }
/// <summary> /// it insert a new data in description, but in table 'bug', just update the update_date. /// </summary> /// <param name="sender">Event Sender</param> /// <param name="e">Event Arguments</param> private void btn_finish_Click(object sender, EventArgs e) { using (SqlConnection con = new SqlConnection(connection)) { con.Open(); DateTime myDateTime = DateTime.Now; string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff"); string newcom = "insert into bug_description (BugID,Class_file,Method,Start_Line_Number,End_Line_Number,project,comment,update_date,Source_code) VALUES('" + label13.Text + "','" + txt_classFile.Text + "','" + txt_method.Text + "','" + txt_startLineNumber.Text + "','" + txt_endLineNumber.Text + "','" + label_project.Text + "','" + txt_comment.Text + "','" + sqlFormattedDate + "','" + label_sourceCode.Text + "')"; SqlCommand cmd = new SqlCommand(newcom, con); cmd.ExecuteNonQuery(); } DateTime myDateTime1 = DateTime.Now; string history = @"C:\Users\Reggie\source\repos\history\history.txt"; if (Directory.Exists(history)) { Directory.Delete(history, true); } string sqlFormattedDate1 = myDateTime1.ToString("yyyy-MM-dd HH:mm:ss.fff"); string[] lines = { txt_comment.Text, label13.Text, txt_method.Text, txt_startLineNumber.Text, txt_endLineNumber.Text, label_project.Text, sqlFormattedDate1 }; // The using statement automatically flushes AND CLOSES the stream and calls // IDisposable.Dispose on the stream object. // NOTE: do not use FileStream for text files because it writes bytes, but StreamWriter // encodes the output as text. using (System.IO.StreamWriter file = new System.IO.StreamWriter(history)) { foreach (string line in lines) { file.WriteLine(line); } } //commit and push to bitbucket GitRepositoryManager grm = new GitRepositoryManager("*****@*****.**", "Cloud19961008", "https://[email protected]/reggiecril/history.git", @"C:\Users\Reggie\source\repos\history"); String message = txt_comment.Text; Signature author = new Signature(this.label3.Text, "email", DateTime.Now); Signature commiter = author; CommitOptions co = new CommitOptions(); grm.CommitAllChanges(message, author, commiter, co); grm.PushCommits("history", @"refs/heads/master"); //back to home page load(); }
public void Init_FlowWithExistingBranches(string masterBranch, string devBranch) { using (_testRepository = new Repository(_testPath)) { var settings = new GitFlowRepoSettings(); Signature committer = author; var opts = new CommitOptions { AllowEmptyCommit = true }; _testRepository.Commit("Initial commit", author, committer, opts); TestHelpers.CreateLocalTestBranch(_testRepository, masterBranch, GitFlowSetting.Master, settings); TestHelpers.CreateLocalTestBranch(_testRepository, devBranch, GitFlowSetting.Develop, settings); _testRepository.Flow().Init(settings, author); Assert.NotNull(_testRepository.Branches.FirstOrDefault( x => string.Equals(x.FriendlyName, settings.GetSetting(GitFlowSetting.Master), StringComparison.OrdinalIgnoreCase))); Assert.NotNull(_testRepository.Branches.FirstOrDefault( x => string.Equals(x.FriendlyName, settings.GetSetting(GitFlowSetting.Develop), StringComparison.OrdinalIgnoreCase))); } }
private static void RegisterPushSubcommand(CommandLineApplication packagesCmd, ReportsFactory reportsFactory) { packagesCmd.Command("push", c => { c.Description = "Incremental copy of files from local packages to remote location"; var argRemote = c.Argument("[remote]", "Path to remote packages folder"); var argSource = c.Argument("[source]", "Path to source packages folder, default is current directory"); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { c.ShowRootCommandFullNameAndVersion(); var reports = reportsFactory.CreateReports(quiet: false); // Implicitly commit changes before push var commitOptions = new CommitOptions { Reports = reports, SourcePackages = argSource.Value }; var commitCommand = new CommitCommand(commitOptions); var success = commitCommand.Execute(); if (!success) { return 1; } var pushOptions = new PushOptions { Reports = reports, SourcePackages = argSource.Value, RemotePackages = argRemote.Value }; var pushCommand = new PushCommand(pushOptions); success = pushCommand.Execute(); return success ? 0 : 1; }); }); }
public void CommitFilesToGitHub(SolutionFileInfo solutionFileInfo, string solutionFilePath, string fileUnmanaged, string fileManaged, string webResources, string multilpleSolutionsImportPSPathVirtual, string solutionToBeImportedPSPathVirtual) { try { using (var repo = new Repository(this.localFolder.FullName)) { this.AddRepositoryIndexes(fileUnmanaged, repo); this.AddRepositoryIndexes(fileManaged, repo); this.AddWebResourcesToRepository(webResources, repo); //// todo: add extracted solution files to repository this.AddExtractedSolutionToRepository(solutionFileInfo, repo); repo.Index.Add(solutionFilePath.Replace(this.localFolder.FullName, string.Empty)); repo.Index.Add(multilpleSolutionsImportPSPathVirtual.Replace(this.localFolder.FullName, string.Empty)); repo.Index.Add(solutionToBeImportedPSPathVirtual.Replace(this.localFolder.FullName, string.Empty)); var offset = DateTimeOffset.Now; Signature author = new Signature(this.authorName, this.authorEmail, offset); Signature committer = new Signature(this.committerName, this.committerEmail, offset); CommitOptions commitOptions = new CommitOptions { AllowEmptyCommit = false }; var commit = repo.Commit(solutionFileInfo.Message, author, committer); string commitIds = solutionFileInfo.Solution.GetAttributeValue <string>(Constants.SourceControlQueueAttributeNameForCommitIds); if (string.IsNullOrEmpty(commitIds)) { commitIds = string.Empty; } commitIds += string.Format("Commit Info <br/><a href='{0}/commit/{1}'>{2}</a>", this.repoUrl.Replace(".git", ""), commit.Id.Sha, commit.Message); solutionFileInfo.Solution[Constants.SourceControlQueueAttributeNameForCommitIds] = commitIds; } } catch (EmptyCommitException ex) { Singleton.SolutionFileInfoInstance.WebJobsLog.AppendLine(" " + ex.Message + "<br>"); Console.WriteLine(ex.Message); } }
public static void Init(this Flow gitFlow, GitFlowRepoSettings settings, Signature author) { var repo = gitFlow.Repository; //Only init if it is not initialized if (gitFlow.IsInitialized()) { //TODO: Does Init do anything if already initialized? Is it sufficient to just check the ConfigValues? Should it check branch existance as well? return; } if (gitFlow.IsEmptyRepository()) { Log("New Repository Detected - Creating Master Branch"); //TODO: Decide if Init should create necesarry branches too? //Create Master branch Signature committer = author; var opts = new CommitOptions { AllowEmptyCommit = true }; repo.Commit("Initial commit", author, committer, opts); //Now make Dev } SetupMasterBranch(repo, settings.Settings[GitFlowSetting.Master], author); SetupDevBranch(repo, settings.Settings[GitFlowSetting.Develop], settings.Settings[GitFlowSetting.Master], author); //TODO.. Repo has branches settings.Settings .ToList() .ForEach(item => repo.Config.Set(GetConfigKey(item.Key), item.Value, settings.ConfigurationLocation) ); Log("Init Complete"); }
private void Commit(string gitPath, SvnChangeset set) { CommitOptions commitOptions; commitOptions = new CommitOptions { AllowEmptyCommit = Settings.Default.AllowEmptyCommits }; using (Repository repo = new Repository(gitPath)) { Signature author; Signature committer; Commit commit; Commands.Stage(repo, "*"); author = new Signature(set.Author.Name, set.Author.EmailAddress, set.Time); committer = author; commit = repo.Commit(set.Log, author, committer, commitOptions); } }
public void Commit(string message, string author, DateTimeOffset when, CommitOptions options) { try { MailAddress mailAddress = new MailAddress(string.IsNullOrEmpty(author) ? Author : author); var signature = new Signature(mailAddress.DisplayName, mailAddress.Address, when); var commit = _repo.Commit(message, signature, signature, options); Trace.TraceInformation("[{0} ({1}) {2}] {3}", _repo.Head.FriendlyName, _repo.Head.CanonicalName, commit.Id.ToString(7), commit.MessageShort); } catch (FormatException) { throw new GitException(string.Format("author '{0}' is not 'Name <email>' and matches no existing author", author)); } catch (LibGit2SharpException ex) { throw new GitException("Commit Failed.", ex); } }
public static IEnumerable <string> Commit(CommitOptions options = default) { yield return("commit"); yield return("--quiet"); yield return("--allow-empty-message"); yield return("--file"); yield return("-"); if (options.All == true) { yield return("--all"); } if (options.Amend == true) { yield return("--amend"); } if (options.Signoff == true) { yield return("--signoff"); } if (options.SignCommit == true) { yield return("-S"); } if (options.Empty == true) { yield return("--allow-empty"); } }
public int Main(string[] args) { var app = new CommandLineApplication(); app.Name = "kpm"; var optionVerbose = app.Option("-v|--verbose", "Show verbose output", CommandOptionType.NoValue); app.HelpOption("-?|-h|--help"); app.VersionOption("--version", GetVersion()); // Show help information if no subcommand/option was specified app.OnExecute(() => { app.ShowHelp(); return 2; }); app.Command("restore", c => { c.Description = "Restore packages"; var argRoot = c.Argument("[root]", "Root of all projects to restore. It can be a directory, a project.json, or a global.json."); var optSource = c.Option("-s|--source <FEED>", "A list of packages sources to use for this command", CommandOptionType.MultipleValue); var optFallbackSource = c.Option("-f|--fallbacksource <FEED>", "A list of packages sources to use as a fallback", CommandOptionType.MultipleValue); var optProxy = c.Option("-p|--proxy <ADDRESS>", "The HTTP proxy to use when retrieving packages", CommandOptionType.SingleValue); var optNoCache = c.Option("--no-cache", "Do not use local cache", CommandOptionType.NoValue); var optPackageFolder = c.Option("--packages", "Path to restore packages", CommandOptionType.SingleValue); var optQuiet = c.Option("--quiet", "Do not show output such as HTTP request/cache information", CommandOptionType.NoValue); var optIgnoreFailedSources = c.Option("--ignore-failed-sources", "Ignore failed remote sources if there are local packages meeting version requirements", CommandOptionType.NoValue); c.HelpOption("-?|-h|--help"); c.OnExecute(async () => { var command = new RestoreCommand(_environment); command.Reports = CreateReports(optionVerbose.HasValue(), optQuiet.HasValue()); command.RestoreDirectory = argRoot.Value; command.Sources = optSource.Values; command.FallbackSources = optFallbackSource.Values; command.NoCache = optNoCache.HasValue(); command.PackageFolder = optPackageFolder.Value(); command.IgnoreFailedSources = optIgnoreFailedSources.HasValue(); if (optProxy.HasValue()) { Environment.SetEnvironmentVariable("http_proxy", optProxy.Value()); } var success = await command.ExecuteCommand(); return success ? 0 : 1; }); }); app.Command("bundle", c => { c.Description = "Bundle application for deployment"; var argProject = c.Argument("[project]", "Path to project, default is current directory"); var optionOut = c.Option("-o|--out <PATH>", "Where does it go", CommandOptionType.SingleValue); var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "The configuration to use for deployment (Debug|Release|{Custom})", CommandOptionType.SingleValue); var optionOverwrite = c.Option("--overwrite", "Remove existing files in target folders", CommandOptionType.NoValue); var optionNoSource = c.Option("--no-source", "Compiles the source files into NuGet packages", CommandOptionType.NoValue); var optionRuntime = c.Option("--runtime <RUNTIME>", "Name or full path of the runtime folder to include", CommandOptionType.MultipleValue); var optionNative = c.Option("--native", "Build and include native images. User must provide targeted CoreCLR runtime versions along with this option.", CommandOptionType.NoValue); var optionWwwRoot = c.Option("--wwwroot <NAME>", "Name of public folder in the project directory", CommandOptionType.SingleValue); var optionWwwRootOut = c.Option("--wwwroot-out <NAME>", "Name of public folder in the bundle, can be used only when the '--wwwroot' option or 'webroot' in project.json is specified", CommandOptionType.SingleValue); var optionQuiet = c.Option("--quiet", "Do not show output such as source/destination of bundled files", CommandOptionType.NoValue); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var options = new BundleOptions { OutputDir = optionOut.Value(), ProjectDir = argProject.Value ?? System.IO.Directory.GetCurrentDirectory(), Configuration = optionConfiguration.Value() ?? "Debug", RuntimeTargetFramework = _environment.RuntimeFramework, WwwRoot = optionWwwRoot.Value(), WwwRootOut = optionWwwRootOut.Value() ?? optionWwwRoot.Value(), Overwrite = optionOverwrite.HasValue(), NoSource = optionNoSource.HasValue(), Runtimes = optionRuntime.HasValue() ? string.Join(";", optionRuntime.Values). Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) : new string[0], Native = optionNative.HasValue(), Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue()) }; var manager = new BundleManager(_hostServices, options); if (!manager.Bundle()) { return -1; } return 0; }); }); app.Command("pack", c => { c.Description = "Build NuGet packages for the project in given directory"; var optionFramework = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue); var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue); var optionOut = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue); var optionDependencies = c.Option("--dependencies", "Copy dependencies", CommandOptionType.NoValue); var optionQuiet = c.Option("--quiet", "Do not show output such as source/destination of nupkgs", CommandOptionType.NoValue); var argProjectDir = c.Argument("[project]", "Project to pack, default is current directory"); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var buildOptions = new BuildOptions(); buildOptions.OutputDir = optionOut.Value(); buildOptions.ProjectDir = argProjectDir.Value ?? Directory.GetCurrentDirectory(); buildOptions.Configurations = optionConfiguration.Values; buildOptions.TargetFrameworks = optionFramework.Values; buildOptions.GeneratePackages = true; buildOptions.Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue()); var projectManager = new BuildManager(_hostServices, buildOptions); if (!projectManager.Build()) { return -1; } return 0; }); }); app.Command("build", c => { c.Description = "Produce assemblies for the project in given directory"; var optionFramework = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue); var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue); var optionOut = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue); var optionQuiet = c.Option("--quiet", "Do not show output such as dependencies in use", CommandOptionType.NoValue); var argProjectDir = c.Argument("[project]", "Project to build, default is current directory"); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var buildOptions = new BuildOptions(); buildOptions.OutputDir = optionOut.Value(); buildOptions.ProjectDir = argProjectDir.Value ?? Directory.GetCurrentDirectory(); buildOptions.Configurations = optionConfiguration.Values; buildOptions.TargetFrameworks = optionFramework.Values; buildOptions.GeneratePackages = false; buildOptions.Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue()); var projectManager = new BuildManager(_hostServices, buildOptions); if (!projectManager.Build()) { return -1; } return 0; }); }); app.Command("add", c => { c.Description = "Add a dependency into dependencies section of project.json"; var argName = c.Argument("[name]", "Name of the dependency to add"); var argVersion = c.Argument("[version]", "Version of the dependency to add"); var argProject = c.Argument("[project]", "Path to project, default is current directory"); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var reports = CreateReports(optionVerbose.HasValue(), quiet: false); var command = new AddCommand(); command.Reports = reports; command.Name = argName.Value; command.Version = argVersion.Value; command.ProjectDir = argProject.Value; var success = command.ExecuteCommand(); return success ? 0 : 1; }); }); app.Command("install", c => { c.Description = "Install the given dependency"; var argName = c.Argument("[name]", "Name of the dependency to add"); var argVersion = c.Argument("[version]", "Version of the dependency to add, default is the latest version."); var argProject = c.Argument("[project]", "Path to project, default is current directory"); var optSource = c.Option("-s|--source <FEED>", "A list of packages sources to use for this command", CommandOptionType.MultipleValue); var optFallbackSource = c.Option("-f|--fallbacksource <FEED>", "A list of packages sources to use as a fallback", CommandOptionType.MultipleValue); var optProxy = c.Option("-p|--proxy <ADDRESS>", "The HTTP proxy to use when retrieving packages", CommandOptionType.SingleValue); var optNoCache = c.Option("--no-cache", "Do not use local cache", CommandOptionType.NoValue); var optPackageFolder = c.Option("--packages", "Path to restore packages", CommandOptionType.SingleValue); var optQuiet = c.Option("--quiet", "Do not show output such as HTTP request/cache information", CommandOptionType.NoValue); var optIgnoreFailedSources = c.Option("--ignore-failed-sources", "Ignore failed remote sources if there are local packages meeting version requirements", CommandOptionType.NoValue); c.HelpOption("-?|-h|--help"); c.OnExecute(async () => { var reports = CreateReports(optionVerbose.HasValue(), optQuiet.HasValue()); var addCmd = new AddCommand(); addCmd.Reports = reports; addCmd.Name = argName.Value; addCmd.Version = argVersion.Value; addCmd.ProjectDir = argProject.Value; var restoreCmd = new RestoreCommand(_environment); restoreCmd.Reports = reports; restoreCmd.RestoreDirectory = argProject.Value; restoreCmd.Sources = optSource.Values; restoreCmd.FallbackSources = optFallbackSource.Values; restoreCmd.NoCache = optNoCache.HasValue(); restoreCmd.PackageFolder = optPackageFolder.Value(); restoreCmd.IgnoreFailedSources = optIgnoreFailedSources.HasValue(); if (optProxy.HasValue()) { Environment.SetEnvironmentVariable("http_proxy", optProxy.Value()); } var installCmd = new InstallCommand(addCmd, restoreCmd); installCmd.Reports = reports; var success = await installCmd.ExecuteCommand(); return success ? 0 : 1; }); }); app.Command("packages", packagesCommand => { packagesCommand.Description = "Commands related to managing local and remote packages folders"; packagesCommand.HelpOption("-?|-h|--help"); packagesCommand.OnExecute(() => { packagesCommand.ShowHelp(); return 2; }); packagesCommand.Command("add", c => { c.Description = "Add a NuGet package to the specified packages folder"; var argNupkg = c.Argument("[nupkg]", "Path to a NuGet package"); var argSource = c.Argument("[source]", "Path to packages folder"); c.HelpOption("-?|-h|--help"); c.OnExecute(async () => { var options = new AddOptions { Reports = CreateReports(optionVerbose.HasValue(), quiet: false), SourcePackages = argSource.Value, NuGetPackage = argNupkg.Value }; var command = new Packages.AddCommand(options); var success = await command.Execute(); return success ? 0 : 1; }); }); packagesCommand.Command("push", c => { c.Description = "Incremental copy of files from local packages to remote location"; var argRemote = c.Argument("[remote]", "Path to remote packages folder"); var argSource = c.Argument("[source]", "Path to source packages folder, default is current directory"); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var reports = CreateReports(optionVerbose.HasValue(), quiet: false); // Implicitly commit changes before push var commitOptions = new CommitOptions { Reports = reports, SourcePackages = argSource.Value }; var commitCommand = new CommitCommand(commitOptions); var success = commitCommand.Execute(); if (!success) { return 1; } var pushOptions = new PushOptions { Reports = reports, SourcePackages = argSource.Value, RemotePackages = argRemote.Value }; var pushCommand = new PushCommand(pushOptions); success = pushCommand.Execute(); return success ? 0 : 1; }); }); packagesCommand.Command("pull", c => { c.Description = "Incremental copy of files from remote location to local packages"; var argRemote = c.Argument("[remote]", "Path to remote packages folder"); var argSource = c.Argument("[source]", "Path to source packages folder, default is current directory"); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var reports = CreateReports(optionVerbose.HasValue(), quiet: false); bool success; if (Directory.Exists(argSource.Value)) { // Implicitly commit changes before pull var commitOptions = new CommitOptions { Reports = reports, SourcePackages = argSource.Value }; var commitCommand = new CommitCommand(commitOptions); success = commitCommand.Execute(); if (!success) { return 1; } } var pullOptions = new PullOptions { Reports = reports, SourcePackages = argSource.Value, RemotePackages = argRemote.Value }; var pullCommand = new PullCommand(pullOptions); success = pullCommand.Execute(); return success ? 0 : 1; }); }); }); app.Command("list", c => { c.Description = "Print the dependencies of a given project."; var showAssemblies = c.Option("-a|--assemblies", "Show the assembly files that are depended on by given project.", CommandOptionType.NoValue); var framework = c.Option("--framework", "Show dependencies for only the given framework.", CommandOptionType.SingleValue); var runtimeFolder = c.Option("--runtime", "The folder containing all available framework assemblies.", CommandOptionType.SingleValue); var argProject = c.Argument("[project]", "The path to project. If omitted, the command will use the project in the current directory."); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var options = new DependencyListOptions(CreateReports(verbose: true, quiet: false), argProject, framework) { ShowAssemblies = showAssemblies.HasValue(), RuntimeFolder = runtimeFolder.Value(), }; if (!options.Valid) { if (options.Project == null) { options.Reports.Error.WriteLine(string.Format("A project could not be found in {0}.", options.Path).Red()); return 1; } else { options.Reports.Error.WriteLine("Invalid options.".Red()); return 2; } } var command = new DependencyListCommand(options); return command.Execute(); }); }); // "kpm wrap" invokes MSBuild, which is not available on *nix if (!PlatformHelper.IsMono) { app.Command("wrap", c => { c.Description = "Wrap a csproj into a project.json, which can be referenced by project.json files"; var argPath = c.Argument("[path]", "Path to csproj to be wrapped"); var optConfiguration = c.Option("--configuration <CONFIGURATION>", "Configuration of wrapped project, default is 'debug'", CommandOptionType.SingleValue); var optMsBuildPath = c.Option("--msbuild <PATH>", @"Path to MSBuild, default is '%ProgramFiles%\MSBuild\14.0\Bin\MSBuild.exe'", CommandOptionType.SingleValue); var optInPlace = c.Option("-i|--in-place", "Generate or update project.json files in project directories of csprojs", CommandOptionType.NoValue); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var reports = CreateReports(optionVerbose.HasValue(), quiet: false); var command = new WrapCommand(); command.Reports = reports; command.CsProjectPath = argPath.Value; command.Configuration = optConfiguration.Value(); command.MsBuildPath = optMsBuildPath.Value(); command.InPlace = optInPlace.HasValue(); var success = command.ExecuteCommand(); return success ? 0 : 1; }); }); } return app.Execute(args); }
/// <summary> /// Perform an operation inside of a transaction. The transaction is committed /// if the operation completes normally. /// </summary> /// <param name="block">The operation to perform.</param> /// <param name="options">Commit option for the transaction.</param> /// <returns>The Connection that performed the transaction.</returns> private Connection UsingTransaction(Action block, CommitOptions options) { using (var trx = this.BeginTransaction()) { block(); trx.Commit(options); } return this; }
/// <summary> /// Commit a transaction. This object must be in a transaction. /// </summary> /// <param name="options"> /// Options for transaction commit. /// </param> public abstract void Commit(CommitOptions options);
public void BuildAndRegisterConcepts() { // Setting the default agency like this means // we don't need to manually set it for every // item we create. VersionableBase.DefaultAgencyId = "int.example"; // Create a scheme to hold the concepts. ConceptScheme scheme = new ConceptScheme(); scheme.Label.Current = "Transportation Modes"; // Create 6 concepts, setting up a small hierarchy. Concept transportMode = new Concept(); transportMode.Label.Current = "Transport Mode"; Concept auto = new Concept(); auto.SubclassOf.Add(transportMode); auto.Label.Current = "Auto"; Concept car = new Concept(); car.SubclassOf.Add(auto); car.Label.Current = "Car"; Concept truck = new Concept(); truck.SubclassOf.Add(auto); truck.Label.Current = "Truck"; Concept bike = new Concept(); bike.SubclassOf.Add(transportMode); bike.Label.Current = "Bike"; Concept walk = new Concept(); walk.SubclassOf.Add(transportMode); walk.Label.Current = "Walk"; // Add the concpts to the scheme. scheme.Concepts.Add(transportMode); scheme.Concepts.Add(auto); scheme.Concepts.Add(car); scheme.Concepts.Add(truck); scheme.Concepts.Add(bike); scheme.Concepts.Add(walk); var client = GetClient(); CommitOptions options = new CommitOptions(); // Gather all the scheme and all the items in the scheme, // so we can register them with a single call to the repository. ItemGathererVisitor gatherer = new ItemGathererVisitor(); scheme.Accept(gatherer); // Register the items with the repository. client.RegisterItems(gatherer.FoundItems, options); // Alternatively, we could register the items one at a time, like this. //client.RegisterItem(scheme, options); //client.RegisterItem(transportMode, options); //client.RegisterItem(auto, options); //client.RegisterItem(car, options); //client.RegisterItem(truck, options); //client.RegisterItem(bike, options); //client.RegisterItem(walk, options); }
/// <summary> /// Get the CommitTransactionGrbit that should be used for the given options. /// </summary> /// <param name="options">The commit options.</param> /// <returns>The commit grbit for the options.</returns> internal static CommitTransactionGrbit GrbitFromOptions(CommitOptions options) { return CommitOptions.Fast == options ? CommitTransactionGrbit.LazyFlush : CommitTransactionGrbit.None; }
public int Main(string[] args) { var app = new CommandLineApplication(); app.Name = "dnu"; app.FullName = "Microsoft .NET Development Utility"; var optionVerbose = app.Option("-v|--verbose", "Show verbose output", CommandOptionType.NoValue); app.HelpOption("-?|-h|--help"); app.VersionOption("--version", GetVersion); // Show help information if no subcommand/option was specified app.OnExecute(() => { app.ShowHelp(); return 2; }); app.Command("restore", c => { c.Description = "Restore packages"; var argRoot = c.Argument("[root]", "Root of all projects to restore. It can be a directory, a project.json, or a global.json."); var feedOptions = FeedOptions.Add(c); var optLock = c.Option("--lock", "Creates dependencies file with locked property set to true. Overwrites file if it exists.", CommandOptionType.NoValue); var optUnlock = c.Option("--unlock", "Creates dependencies file with locked property set to false. Overwrites file if it exists.", CommandOptionType.NoValue); var optParallel = c.Option("--parallel", "Restores in parallel when more than one project.json is discovered.", CommandOptionType.NoValue); c.HelpOption("-?|-h|--help"); c.OnExecute(async () => { var command = new RestoreCommand(_environment); command.Reports = CreateReports(optionVerbose.HasValue(), feedOptions.Quiet); command.RestoreDirectory = argRoot.Value; command.FeedOptions = feedOptions; command.Lock = optLock.HasValue(); command.Unlock = optUnlock.HasValue(); command.Parallel = optParallel.HasValue(); if (feedOptions.ProxyOptions.HasValue()) { Environment.SetEnvironmentVariable("http_proxy", feedOptions.Proxy); } var success = await command.ExecuteCommand(); return success ? 0 : 1; }); }); app.Command("publish", c => { c.Description = "Publish application for deployment"; var argProject = c.Argument("[project]", "Path to project, default is current directory"); var optionOut = c.Option("-o|--out <PATH>", "Where does it go", CommandOptionType.SingleValue); var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "The configuration to use for deployment (Debug|Release|{Custom})", CommandOptionType.SingleValue); var optionNoSource = c.Option("--no-source", "Compiles the source files into NuGet packages", CommandOptionType.NoValue); var optionRuntime = c.Option("--runtime <RUNTIME>", "Name or full path of the runtime folder to include, or \"active\" for current runtime on PATH", CommandOptionType.MultipleValue); var optionNative = c.Option("--native", "Build and include native images. User must provide targeted CoreCLR runtime versions along with this option.", CommandOptionType.NoValue); var optionWwwRoot = c.Option("--wwwroot <NAME>", "Name of public folder in the project directory", CommandOptionType.SingleValue); var optionWwwRootOut = c.Option("--wwwroot-out <NAME>", "Name of public folder in the output, can be used only when the '--wwwroot' option or 'webroot' in project.json is specified", CommandOptionType.SingleValue); var optionQuiet = c.Option("--quiet", "Do not show output such as source/destination of published files", CommandOptionType.NoValue); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var options = new PublishOptions { OutputDir = optionOut.Value(), ProjectDir = argProject.Value ?? System.IO.Directory.GetCurrentDirectory(), Configuration = optionConfiguration.Value() ?? "Debug", RuntimeTargetFramework = _environment.RuntimeFramework, WwwRoot = optionWwwRoot.Value(), WwwRootOut = optionWwwRootOut.Value() ?? optionWwwRoot.Value(), NoSource = optionNoSource.HasValue(), Runtimes = optionRuntime.HasValue() ? string.Join(";", optionRuntime.Values). Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) : new string[0], Native = optionNative.HasValue(), Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue()) }; var manager = new PublishManager(_hostServices, options); if (!manager.Publish()) { return -1; } return 0; }); }); app.Command("pack", c => { c.Description = "Build NuGet packages for the project in given directory"; var optionFramework = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue); var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue); var optionOut = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue); var optionDependencies = c.Option("--dependencies", "Copy dependencies", CommandOptionType.NoValue); var optionQuiet = c.Option("--quiet", "Do not show output such as source/destination of nupkgs", CommandOptionType.NoValue); var argProjectDir = c.Argument("[project]", "Project to pack, default is current directory"); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var buildOptions = new BuildOptions(); buildOptions.OutputDir = optionOut.Value(); buildOptions.ProjectDir = argProjectDir.Value ?? Directory.GetCurrentDirectory(); buildOptions.Configurations = optionConfiguration.Values; buildOptions.TargetFrameworks = optionFramework.Values; buildOptions.GeneratePackages = true; buildOptions.Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue()); var projectManager = new BuildManager(_hostServices, buildOptions); if (!projectManager.Build()) { return -1; } return 0; }); }); app.Command("build", c => { c.Description = "Produce assemblies for the project in given directory"; var optionFramework = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue); var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue); var optionOut = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue); var optionQuiet = c.Option("--quiet", "Do not show output such as dependencies in use", CommandOptionType.NoValue); var argProjectDir = c.Argument("[project]", "Project to build, default is current directory"); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var buildOptions = new BuildOptions(); buildOptions.OutputDir = optionOut.Value(); buildOptions.ProjectDir = argProjectDir.Value ?? Directory.GetCurrentDirectory(); buildOptions.Configurations = optionConfiguration.Values; buildOptions.TargetFrameworks = optionFramework.Values; buildOptions.GeneratePackages = false; buildOptions.Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue()); var projectManager = new BuildManager(_hostServices, buildOptions); if (!projectManager.Build()) { return -1; } return 0; }); }); app.Command("install", c => { c.Description = "Install the given dependency"; var argName = c.Argument("[name]", "Name of the dependency to add"); var argVersion = c.Argument("[version]", "Version of the dependency to add, default is the latest version."); var argProject = c.Argument("[project]", "Path to project, default is current directory"); var feedOptions = FeedOptions.Add(c); c.HelpOption("-?|-h|--help"); c.OnExecute(async () => { var reports = CreateReports(optionVerbose.HasValue(), feedOptions.Quiet); var addCmd = new AddCommand(); addCmd.Reports = reports; addCmd.Name = argName.Value; addCmd.Version = argVersion.Value; addCmd.ProjectDir = argProject.Value; var restoreCmd = new RestoreCommand(_environment); restoreCmd.Reports = reports; restoreCmd.FeedOptions = feedOptions; restoreCmd.RestoreDirectory = argProject.Value; if (feedOptions.ProxyOptions.HasValue()) { Environment.SetEnvironmentVariable("http_proxy", feedOptions.Proxy); } var installCmd = new InstallCommand(addCmd, restoreCmd); installCmd.Reports = reports; var success = await installCmd.ExecuteCommand(); return success ? 0 : 1; }); }); app.Command("packages", packagesCommand => { packagesCommand.Description = "Commands related to managing local and remote packages folders"; packagesCommand.HelpOption("-?|-h|--help"); packagesCommand.OnExecute(() => { packagesCommand.ShowHelp(); return 2; }); packagesCommand.Command("add", c => { c.Description = "Add a NuGet package to the specified packages folder"; var argNupkg = c.Argument("[nupkg]", "Path to a NuGet package"); var argSource = c.Argument("[source]", "Path to packages folder"); c.HelpOption("-?|-h|--help"); c.OnExecute(async () => { var options = new AddOptions { Reports = CreateReports(optionVerbose.HasValue(), quiet: false), SourcePackages = argSource.Value, NuGetPackage = argNupkg.Value }; var command = new Packages.AddCommand(options); var success = await command.Execute(); return success ? 0 : 1; }); }); packagesCommand.Command("push", c => { c.Description = "Incremental copy of files from local packages to remote location"; var argRemote = c.Argument("[remote]", "Path to remote packages folder"); var argSource = c.Argument("[source]", "Path to source packages folder, default is current directory"); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var reports = CreateReports(optionVerbose.HasValue(), quiet: false); // Implicitly commit changes before push var commitOptions = new CommitOptions { Reports = reports, SourcePackages = argSource.Value }; var commitCommand = new CommitCommand(commitOptions); var success = commitCommand.Execute(); if (!success) { return 1; } var pushOptions = new PushOptions { Reports = reports, SourcePackages = argSource.Value, RemotePackages = argRemote.Value }; var pushCommand = new PushCommand(pushOptions); success = pushCommand.Execute(); return success ? 0 : 1; }); }); packagesCommand.Command("pull", c => { c.Description = "Incremental copy of files from remote location to local packages"; var argRemote = c.Argument("[remote]", "Path to remote packages folder"); var argSource = c.Argument("[source]", "Path to source packages folder, default is current directory"); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var reports = CreateReports(optionVerbose.HasValue(), quiet: false); bool success; if (Directory.Exists(argSource.Value)) { // Implicitly commit changes before pull var commitOptions = new CommitOptions { Reports = reports, SourcePackages = argSource.Value }; var commitCommand = new CommitCommand(commitOptions); success = commitCommand.Execute(); if (!success) { return 1; } } var pullOptions = new PullOptions { Reports = reports, SourcePackages = argSource.Value, RemotePackages = argRemote.Value }; var pullCommand = new PullCommand(pullOptions); success = pullCommand.Execute(); return success ? 0 : 1; }); }); }); app.Command("list", c => { c.Description = "Print the dependencies of a given project"; var showAssemblies = c.Option("-a|--assemblies", "Show the assembly files that are depended on by given project", CommandOptionType.NoValue); var frameworks = c.Option("--framework <TARGET_FRAMEWORK>", "Show dependencies for only the given frameworks", CommandOptionType.MultipleValue); var runtimeFolder = c.Option("--runtime <PATH>", "The folder containing all available framework assemblies", CommandOptionType.SingleValue); var hideDependents = c.Option("--hide-dependents", "Hide the immediate dependents of libraries referenced in the project", CommandOptionType.NoValue); var resultsFilter = c.Option("--filter <PATTERN>", "Filter the libraries referenced by the project base on their names. The matching pattern supports * and ?", CommandOptionType.SingleValue); var argProject = c.Argument("[project]", "Path to project, default is current directory"); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var options = new DependencyListOptions(CreateReports(verbose: true, quiet: false), argProject) { TargetFrameworks = frameworks.Values, ShowAssemblies = showAssemblies.HasValue(), RuntimeFolder = runtimeFolder.Value(), HideDependents = hideDependents.HasValue(), ResultsFilter = resultsFilter.Value() }; if (!options.Valid) { if (options.Project == null) { options.Reports.Error.WriteLine(string.Format("Unable to locate {0}.".Red(), Runtime.Project.ProjectFileName)); return 1; } else { options.Reports.Error.WriteLine("Invalid options.".Red()); return 2; } } var command = new DependencyListCommand(options, _environment.RuntimeFramework); return command.Execute(); }); }); app.Command("commands", cmd => { cmd.Description = "Commands related to managing application commands (add, remove)"; cmd.HelpOption("-?|-h|--help"); cmd.OnExecute(() => { cmd.ShowHelp(); return 2; }); cmd.Command("install", c => { c.Description = "Installs application commands"; var argPackage = c.Argument("[package]", "The name of the application package"); var argVersion = c.Argument("[version]", "The version of the application package"); var optOverwrite = c.Option("-o|--overwrite", "Overwrites conflicting commands", CommandOptionType.NoValue); var feedOptions = FeedOptions.Add(c); c.HelpOption("-?|-h|--help"); c.OnExecute(async () => { var command = new InstallGlobalCommand( _environment, string.IsNullOrEmpty(feedOptions.TargetPackagesFolder) ? AppCommandsFolderRepository.CreateDefault() : AppCommandsFolderRepository.Create(feedOptions.TargetPackagesFolder)); command.FeedOptions = feedOptions; command.Reports = CreateReports(optionVerbose.HasValue(), feedOptions.Quiet); command.OverwriteCommands = optOverwrite.HasValue(); if (feedOptions.Proxy != null) { Environment.SetEnvironmentVariable("http_proxy", feedOptions.Proxy); } var success = await command.Execute(argPackage.Value, argVersion.Value); return success ? 0 : 1; }); }); cmd.Command("uninstall", c => { c.Description = "Uninstalls application commands"; var argCommand = c.Argument("[command]", "The name of the command to uninstall"); var optNoPurge = c.Option("--no-purge", "Do not try to remove orphaned packages", CommandOptionType.NoValue); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var command = new UninstallCommand( _environment, AppCommandsFolderRepository.CreateDefault(), reports: CreateReports(optionVerbose.HasValue(), quiet: false)); command.NoPurge = optNoPurge.HasValue(); var success = command.Execute(argCommand.Value); return success ? 0 : 1; }); }); }); app.Command("wrap", c => { c.Description = "Wrap a csproj into a project.json, which can be referenced by project.json files"; var argPath = c.Argument("[path]", "Path to csproj to be wrapped"); var optConfiguration = c.Option("--configuration <CONFIGURATION>", "Configuration of wrapped project, default is 'debug'", CommandOptionType.SingleValue); var optMsBuildPath = c.Option("--msbuild <PATH>", @"Path to MSBuild, default is '%ProgramFiles%\MSBuild\14.0\Bin\MSBuild.exe'", CommandOptionType.SingleValue); var optInPlace = c.Option("-i|--in-place", "Generate or update project.json files in project directories of csprojs", CommandOptionType.NoValue); var optFramework = c.Option("-f|--framework", "Target framework of assembly to be wrapped", CommandOptionType.SingleValue); c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var reports = CreateReports(optionVerbose.HasValue(), quiet: false); var command = new WrapCommand(); command.Reports = reports; command.InputFilePath = argPath.Value; command.Configuration = optConfiguration.Value(); command.MsBuildPath = optMsBuildPath.Value(); command.InPlace = optInPlace.HasValue(); command.Framework = optFramework.Value(); var success = command.ExecuteCommand(); return success ? 0 : 1; }); }); return app.Execute(args); }