// Happens when the user presses the save button on the dialog // We validate our server connection before allowing DialogResult.OK private void btnSave_Click(object sender, EventArgs e) { // The lists that store our request and response batches List <JsonCommand> requestList = new List <JsonCommand>(); List <JsonResult> responseList = new List <JsonResult>(); // Create the API get login ticket request object SessionService.getLoginTicket request = new SessionService.getLoginTicket(); // Populate the request fields with our form data request.login = tbUsername.Text; request.password = tbPassword.Text; // Queue up the above request, wrapping it in a JsonCommand object requestList.Add(new JsonCommand(request)); try { // Send the request, it's our responsibility to trap errors here, they should be friendly responseList = CollabServerRequest.Execute(tbServerURL.Text, requestList); } catch (Exception ex) { // TODO: Do something better with exceptions // Tell the user about the low level communication error. e.g. connection refused MessageBox.Show(ex.Message, "Error sending request", MessageBoxButtons.OK, MessageBoxIcon.Error); this.DialogResult = DialogResult.None; // There was an error, don't close the dialog } if (responseList != null && responseList.Count() > 0) // Execute block if we didn't error above { foreach (JsonResult obj in responseList) // There should only be 1 response here { // This block catches errors returned as an error object by the Collab API if (!obj.isError()) // Did the user authenticate successfully? { // Authenticated! // Put the login ticket in a handy place, where the caller can get it this.loginTicket = obj.GetResponse <SessionService.getLoginTicketResponse>().loginTicket; // Let the dialog close with DialogResult.OK, the caller will save form data } else { // Authentication error, tell the user what happened MessageBox.Show(obj.GetErrorString(), "Error returned from server", MessageBoxButtons.OK, MessageBoxIcon.Error); this.DialogResult = DialogResult.None; // There was an error, don't close the dialog } } } }
private void btnRefresh_Click(object sender, EventArgs e) { // The lists that store our request and response batches List <JsonCommand> requestList = new List <JsonCommand>(); List <JsonResult> responseList = new List <JsonResult>(); // Create the API request objects // Authenticate with our token requestList.Add(new JsonCommand( new SessionService.authenticate { login = Properties.Settings.Default.CollabUser, ticket = Properties.Settings.Default.CollabLoginTicket } )); // Get action items requestList.Add(new JsonCommand( new UserService.getActionItems { // no args } )); try { // Send the requests, it's our responsibility to trap errors here, they should be friendly responseList = CollabServerRequest.Execute(Properties.Settings.Default.CollabServerURL, requestList); } catch (Exception ex) { // TODO: Do something better with exceptions // Tell the user about the low level communication error. e.g. connection refused MessageBox.Show(ex.Message, "Error sending request", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (responseList != null && responseList.Count() > 0) // Execute block if we didn't error above { // Get the items in the list, in order List <JsonResult> .Enumerator resultEnum = responseList.GetEnumerator(); resultEnum.MoveNext(); // get the first response try { // first command is authenticate, make sure there's no error. if (resultEnum.Current.isError()) { // Assume the ticket is not valid, and clear out the stored one Properties.Settings.Default.CollabLoginTicket = ""; Properties.Settings.Default.settingsValidated = false; Properties.Settings.Default.Save(); // Stop execution, and display an error throw (new Exception(resultEnum.Current.GetErrorString())); } resultEnum.MoveNext(); // get next command response // make sure we didn't error on action item retrieval if (resultEnum.Current.isError()) { throw (new Exception(resultEnum.Current.GetErrorString())); } // deserialize action items UserService.getActionItemsResponse actItems = resultEnum.Current.GetResponse <UserService.getActionItemsResponse>(); listBox1.BeginUpdate(); listBox1.Items.Clear(); foreach (UserService.ActionItem act in actItems.actionItems) { listBox1.Items.Add(act.text); } listBox1.EndUpdate(); } catch (Exception ex) { // TODO: Add different exception types to differentiate between api errors and potential deserialization explosions MessageBox.Show(ex.Message, "Error returned from server", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
private void btnUpload_Click(object sender, RibbonControlEventArgs e) { Presentation curDoc = Globals.ThisAddIn.Application.ActivePresentation; string zipFileName = Path.GetTempPath().TrimEnd('\\') + "\\temp_ccollabpptaddinupload.zip"; string docFileName = Path.GetTempPath().TrimEnd('\\') + "\\temp_ccollabpptaddinupload.pptx"; string curDocMD5 = ""; string oldFilePath = ""; string oldFileName = ""; int revID = 0; string uploadComment = ""; string revTitle = ""; // Make sure the current document is saved before we do anything while ((curDoc.Saved == Microsoft.Office.Core.MsoTriState.msoFalse) || (curDoc.Path.Length < 1)) { // User hasn't saved the current document, prompt them to save it! if (DialogResult.Yes == MessageBox.Show( "You must save the current document before you can upload it to Collaborator for review. Would you like to save now?", "Collaborator by SmartBear", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)) { curDoc.Save(); } else { return; // User didn't say yes to save, cancel the upload request } // Run in a loop to make sure the document has no pending changes. Maybe the save or save as failed. } // Document is saved, next get the review that we want to upload to ReviewSelectDlg revSelectDlg = new ReviewSelectDlg(); if (DialogResult.OK == revSelectDlg.ShowDialog()) { revID = revSelectDlg.selectedReviewId; revTitle = revSelectDlg.tbReviewTitle.Text; uploadComment = revSelectDlg.tbComment.Text; } else { return; // User hit cancel } // Now save an extra copy oldFileName = curDoc.Name; oldFilePath = curDoc.FullName; try { // Quickly save to a temp directory curDoc.SaveAs(docFileName, PpSaveAsFileType.ppSaveAsPDF, Microsoft.Office.Core.MsoTriState.msoTrue); // Now re-save back to the original location to release the file lock on the temp file curDoc.SaveAs(oldFilePath); docFileName += ".pdf"; // Tack on the PDF extension, because Collab doesn't natively support pptx if (File.Exists(zipFileName)) // If we've got an old zip file lying around { File.Delete(zipFileName); // then delete it } // Get the MD5SUM for the document using (var md5 = MD5.Create()) { // Make sure we open with the lowest acces rights possible using (var stream = File.Open(docFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { curDocMD5 = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower(); } } // Create a new zip archive using (ZipArchive newFile = ZipFile.Open(zipFileName, ZipArchiveMode.Create)) { ZipArchiveEntry newEntry = newFile.CreateEntryFromFile(docFileName, curDocMD5, CompressionLevel.Optimal); } } catch (Exception ex) { // Something bad happened MessageBox.Show(ex.Message, "Collaborator by SmartBear", MessageBoxButtons.OK, MessageBoxIcon.Error); return; // Abort the whole operation } // Everything is zipped, let's upload it try { CollabServerRequest.UploadZipFile( Properties.Settings.Default.CollabServerURL, zipFileName, new SessionService.authenticate { login = Properties.Settings.Default.CollabUser, ticket = Properties.Settings.Default.CollabLoginTicket }); } catch (Exception ex) { // TODO: Do something better with exceptions // Tell the user about the low level communication error. e.g. connection refused MessageBox.Show(ex.Message, "Collaborator by SmartBear", MessageBoxButtons.OK, MessageBoxIcon.Error); return; // Abort the whole operation } // The lists that store our request and response batches List <JsonCommand> requestList = new List <JsonCommand>(); List <JsonResult> responseList = new List <JsonResult>(); // If we need to create a new review if (revID == 0) { // Authenticate with our token requestList.Add(new JsonCommand( new SessionService.authenticate { login = Properties.Settings.Default.CollabUser, ticket = Properties.Settings.Default.CollabLoginTicket } )); // Review creation request requestList.Add(new JsonCommand( new ReviewService.createReview { creator = Properties.Settings.Default.CollabUser, title = revTitle } )); try { // Send the requests, it's our responsibility to trap errors here, they should be friendly responseList = CollabServerRequest.Execute(Properties.Settings.Default.CollabServerURL, requestList); } catch (Exception ex) { // TODO: Do something better with exceptions // Tell the user about the low level communication error. e.g. connection refused MessageBox.Show(ex.Message, "Collaborator by SmartBear", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (responseList != null && responseList.Count() > 0) // Execute block if we didn't error above { // Get the items in the list, in order List <JsonResult> .Enumerator resultEnum = responseList.GetEnumerator(); try { resultEnum.MoveNext(); // get the first command response // first command is authenticate, make sure there's no error. if (resultEnum.Current.isError()) { // Error! // Assume the ticket is not valid, and clear out the stored one Properties.Settings.Default.CollabLoginTicket = ""; Properties.Settings.Default.settingsValidated = false; Properties.Settings.Default.Save(); // Stop execution, and display an error throw (new Exception(resultEnum.Current.GetErrorString())); } resultEnum.MoveNext(); // get next command response // get the review ID of the new review if (resultEnum.Current.isError()) { throw (new Exception(resultEnum.Current.GetErrorString())); // Error! } else { revID = resultEnum.Current.GetResponse <ReviewService.createReviewResponse>().reviewId; } } catch (Exception ex) { // TODO: Add different exception types to differentiate between api errors and potential deserialization explosions MessageBox.Show(ex.Message, "Collaborator by SmartBear", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } // Clean up before our next API call requestList.Clear(); responseList.Clear(); } // Create the API request objects // Authenticate with our token requestList.Add(new JsonCommand( new SessionService.authenticate { login = Properties.Settings.Default.CollabUser, ticket = Properties.Settings.Default.CollabLoginTicket } )); // Create version descriptor List <ReviewService.version> vrsns = new List <ReviewService.version>(); vrsns.Add(new ReviewService.version { md5 = curDocMD5, localPath = oldFileName + ".pdf" // Tack on the PDF extension, because Collab doesn't natively support pptx }); // Create changelist descriptor List <ReviewService.changelist> chgLists = new List <ReviewService.changelist>(); chgLists.Add(new ReviewService.changelist { versions = vrsns, commitInfo = new ReviewService.commitInfo { comment = uploadComment } }); // Create addFiles request requestList.Add(new JsonCommand( new ReviewService.addFiles { reviewId = revID, changelists = chgLists, } )); try { // Send the requests, it's our responsibility to trap errors here, they should be friendly responseList = CollabServerRequest.Execute(Properties.Settings.Default.CollabServerURL, requestList); } catch (Exception ex) { // TODO: Do something better with exceptions // Tell the user about the low level communication error. e.g. connection refused MessageBox.Show(ex.Message, "Collaborator by SmartBear", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (responseList != null && responseList.Count() > 0) // Execute block if we didn't error above { // Get the items in the list, in order List <JsonResult> .Enumerator resultEnum = responseList.GetEnumerator(); try { resultEnum.MoveNext(); // get the first command response // first command is authenticate, make sure there's no error. if (resultEnum.Current.isError()) { // Error! // Assume the ticket is not valid, and clear out the stored one Properties.Settings.Default.CollabLoginTicket = ""; Properties.Settings.Default.settingsValidated = false; Properties.Settings.Default.Save(); // Stop execution, and display an error throw (new Exception(resultEnum.Current.GetErrorString())); } resultEnum.MoveNext(); // get next command response // make sure we didn't error on addFiles if (resultEnum.Current.isError()) { throw (new Exception(resultEnum.Current.GetErrorString())); // Error! } // Success! Offer to open up the review. if (DialogResult.Yes == MessageBox.Show( "We've successfully attached \"" + oldFileName + "\" to Review " + revID.ToString() + "!\r\n\r\n" + "Would you like to open it in your browser?", "Collaborator by SmartBear", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)) { System.Diagnostics.Process.Start(Properties.Settings.Default.CollabServerURL + @"/ui#review:id=" + revID.ToString()); } } catch (Exception ex) { // TODO: Add different exception types to differentiate between api errors and potential deserialization explosions MessageBox.Show(ex.Message, "Collaborator by SmartBear", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
static void DoAPITest() { JsonResult result; // used repeatedly WL("Creating CollabAPI() instance"); WL("Server URL: " + serverURL); WL("User Name: " + userName); CollabAPI api = new CollabAPI(serverURL, userName); try { WL("Calling getServerVersion()"); WL("Result: " + api.getServerVersion()); WL("Calling getServerBuild()"); WL("Result: " + api.getServerBuild()); WL("Calling getMinimumJavaClientBuild()"); WL("Result: " + api.getMinimumJavaClientBuild()); WL("Calling checkTicketValidity()"); WL("Result: " + api.checkTicketValidity().ToString()); WL("Calling getLoginTicket()"); WL("Password: "******"Received Login Ticket: " + result.GetResponse <SessionService.getLoginTicketResponse>().loginTicket); } else { WL(result.GetErrorString()); } WL("Calling checkTicketValidity()"); WL("Result: " + api.checkTicketValidity().ToString()); WL("Calling clearLoginTicket()"); api.clearLoginTicket(); WL("Calling checkTicketValidity()"); WL("Result: " + api.checkTicketValidity().ToString()); WL("Calling getLoginTicket()"); result = api.getLoginTicket(userPass); WL("Password: "******"Received Login Ticket: " + result.GetResponse <SessionService.getLoginTicketResponse>().loginTicket); } else { WL(result.GetErrorString()); } WL("Calling createReview()"); result = api.createReview(); // ======================================================================================================== // This block creates 500 reviews in a single request // ======================================================================================================== #if false List <JsonCommand> requestList = new List <JsonCommand>(); // Add the API authenticate command requestList.Add(new JsonCommand(new SessionService.authenticate() { login = api.userName, ticket = api.userTicket })); // Create tons of reviews! for (int i = 1; i < 500; i++) { requestList.Add(new JsonCommand(new ReviewService.createReview { creator = api.userName, title = "Test Review " + i.ToString() })); } CollabServerRequest.Execute(api.serverURL, requestList); #endif // ======================================================================================================== // ======================================================================================================== // ======================================================================================================== if (!result.isError()) { WL("New Review Id: " + result.GetResponse <ReviewService.createReviewResponse>().reviewId.ToString()); } else { WL(result.GetErrorString()); } WL("Calling createReview(\"API Test Review\")"); result = api.createReview("API Test Review"); if (!result.isError()) { WL("New Review Id: " + result.GetResponse <ReviewService.createReviewResponse>().reviewId.ToString()); } else { WL(result.GetErrorString()); } WL("Calling getLoginTicket()"); result = api.getLoginTicket(userPass); WL("Password: "******"Received Login Ticket: " + result.GetResponse <SessionService.getLoginTicketResponse>().loginTicket); } else { WL(result.GetErrorString()); } WL("Calling getSuggestedReviews()"); result = api.getSuggestedReviews(UserService.SuggestionType.UPLOAD, "", 5000); if (!result.isError()) { UserService.SuggestedReviewsResponse response = result.GetResponse <UserService.SuggestedReviewsResponse>(); WL("Received " + response.suggestedReviews.Count().ToString() + " results:"); foreach (UserService.SuggestedReview sug in response.suggestedReviews) { WL(" Review Id: " + sug.reviewId.ToString()); WL(" Description: " + sug.displayText); WL(" Modified: " + sug.lastModified.ToString()); WL(" Has Changelist: " + sug.containsChangelist.ToString()); WL(""); } } else { WL(result.GetErrorString()); } } catch (Exception ex) { WL(ex.Message); } // We're done WL(); WL("Press any key to exit."); Console.ReadKey(true); }