- Survey Repository
- Survey Development Studio
- PocketSurvey
- Moving On
Survey Development Studio
So far in this chapter we've been talking only about the Survey Repository Web service and all the back-end code that supports it. Now, we're going to talk about the Survey Development Studio Windows Forms application and all its supporting code. While we may have covered a lot of code in the previous sections, we have by no means covered all the code. If you understand the basic concepts behind the code we're discussing in this chapter, you should definitely take the time to read through the code within Visual Studio .NET. There is no substitute for the understanding you can achieve just by getting your hands dirty and digging through the code for a while.
The Survey Profile Editor
Earlier in this chapter you saw a little bit of how the profile editor works when we took a tour of the application and how the application works. The following sections take you through some of the highlights of building and editing a survey profile and the code that makes it all happen.
Editing Questions
Editing questions with the Survey Development Studio application is fairly straightforward. When you have selected a question on the survey profile, you can click the Edit button. You are then prompted for the short and long versions of the question, as well as the question type. If the question type is one that requires a list of items to be presented to the user, you can select that list or create a new list from within the question editor.
Prompting to Save Changes
Because the Survey Development Studio application is an MDI application, it is possible to have open a document (in this case, a survey profile) that has not had the recent changes saved. One thing I decided to build into the Survey Development Suite to illustrate one of the often-overlooked properties of an MDI application is the ability to detect when the user attempts to close a document and automatically save that document if the user chooses.
This functionality hinges on the Closing event. Listing 3.10 shows the Closing event handler and some of the other methods related to saving changes. All the code in this listing is part of the frmSurvey form class.
Listing 3.10 SurveyV1\SurveyStudio\frmSurvey.cs The frmSurvey_Closing Event Handler and Other Related Event Handlers
private void frmSurvey_Closing(object sender, System.ComponentModel.CancelEventArgs e) { DialogResult dr = MessageBox.Show(this, "You are about to close a Survey Profile, would you like to save?", this.Text, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); switch (dr) { case DialogResult.Cancel: e.Cancel = true; break; case DialogResult.Yes: menuItem8_Click(sender, e); CloseChildWindows(); break; case DialogResult.No: CloseChildWindows(); break; } } private void menuItem8_Click(object sender, System.EventArgs e) { if (currentFileName == string.Empty) SaveSurveyAs(); else SaveSurvey(); MessageBox.Show(this, "Survey Profile (" + currentFileName + ") has been saved to disk.", "Save Profile", MessageBoxButtons.OK, MessageBoxIcon.Information ); } private void SaveSurvey() { surveyProfile.WriteXml( currentFileName ); } private void SaveSurveyAs() { if (saveFileDialog1.ShowDialog() == DialogResult.OK) { currentFileName = saveFileDialog1.FileName; SaveSurvey(); } }
The frmSurvey_Closing event handler is called every time the form is about to be closed, regardless of what action triggered the closing. This means that it will be triggered if the Close() method is called programmatically or if the user clicks the Close button.
When the Close() method is called, we ask the user if he or she wants to save the profile, if he or she wants to cancel (and therefore not close the profile form), or if he or she wants to continue closing without saving.
You can see that saving the survey profile is as simple as calling the WriteXml method of the typed data set that contains all the survey profile information.
Another thing that you might notice is that we invoke a method called CloseChildWindows. This method is responsible for closing all the windows that are only relevant within the context of the survey profile window. The following section deals with managing MDI child windows to keep the user interface clean.
Code Tour: Managing MDI Child Windows
Windows Forms has built-in support for MDI parents and child windows. If you close an MDI parent, all the child windows close. However, you cannot make an MDI child window the logical parent of another window.
In our case, the survey profile window is the logical parent of all sub-editors you can launch based on that profile, such as questions. This is a problem because we need to have more logic involved in which windows can be open at any given time. One solution to this is to make the question editors modal. However, this would preclude us from being able to have more than one profile open at a time; that's a sacrifice I didn't want to make.
The workaround here is really just thatnothing more than a workaround. Each time a question editor is loaded, the instance is added to a collection of question editors that each profile window maintains. When that profile window is closed, the collection is then iterated through, allowing all the open question editors to be closed.
A handy side effect of this approach is that when the user tries to edit an existing question, we can go through the collection of question editor windows and look for one that is already open for that question. If one is open, we can simply bring it to the foreground instead of creating a new window. We definitely don't want to have two windows open and editing the same data. Listing 3.11 shows some of the various event handlers within the code that are responsible for maintaining the MDI child windows.
Listing 3.11 SurveyV1\SurveyStudio\frmSurvey.cs Various Event Handlers That Deal with Managing MDI Child Windows
private void button1_Click(object sender, System.EventArgs e) { SurveyProfile.Question question = surveyProfile.Questions.NewQuestion(); surveyProfile.Questions.AddQuestion( question ); frmQuestion newQuestion = new frmQuestion( this, question.ID ); newQuestion.MdiParent = this.MdiParent; newQuestion.Show(); questionEditors.Add( newQuestion ); } public void RemoveQuestionEditor( frmQuestion qeditor ) { questionEditors.Remove( qeditor ); } private void button6_Click(object sender, System.EventArgs e) { int questionId = surveyProfile.Questions[ dgQuestions.CurrentRowIndex ].ID; string surveyId = surveyProfile.Profiles[0].GlobalID; bool alreadyOpen = false; foreach (object qe in questionEditors) { frmQuestion fq = (frmQuestion)qe; if ((fq.questionId == questionId) && (fq.SurveyID == surveyId) ) { alreadyOpen = true; fq.Focus(); break; } } if (!alreadyOpen) { frmQuestion currentQuestion = new frmQuestion( this, questionId ); currentQuestion.MdiParent = this.MdiParent; currentQuestion.Show(); currentQuestion.Focus(); questionEditors.Add( currentQuestion ); } } private void CloseChildWindows() { if (contactManager != null) { contactManager.Close(); contactManager.Dispose(); } foreach (object qe in questionEditors) { ((frmQuestion)qe).Close(); ((frmQuestion)qe).Dispose(); } }
The button1_Click event handler creates a new question and loads a new question editor to allow the user to enter the details for that question. The button6_Click handler is invoked when the user chooses to edit the currently selected question.
The ID of the question is obtained from the data set. Then the list of question editor forms is iterated through. If an open question editor is found that has the appropriate question ID, that form is then brought to the foreground with the Focus() method. Otherwise, a new form is created to manage the selected question, the form instance is added to the collection of editors, and then the form instance is opened.
All this wouldn't work if the question editor didn't have some way of removing its own instance from the editor collection when it closes because the parent form doesn't inherently know when child forms close. This is because we're going one level deeper than the supported MDI framework, and we have to do all the parent/child management on our own.
The question editor form has a Closing event handler of its own:
private void frmQuestion_Closing(object sender, System.ComponentModel.CancelEventArgs e) { this.parentForm.RemoveQuestionEditor( this ); }
The parentForm variable is a variable of type frmSurvey and is set at the time that the question editor is instantiated. This serves to link the question editors to the parent survey editor, allowing the user to have multiple survey profiles open without getting the question editors mixed up. The frmQuestion_Closing method removes the current question editor from the parent survey profile form's editor list when the form closes. This completes the custom implementation of parent/child forms at a level beneath what Windows Forms already provides in the form of an MDI application.
Code Tour: The Run Editor
The run editor form consists of a tab control. The first tab contains a list of all the response sheets submitted for the current run. The second tab, which is read-only, contains a list of all the respondents who have submitted sheets. Note that not every sheet needs to have a specific respondent, so you may often see more response sheets than respondents. From the main form, you can create a new sheet, edit an existing sheet, remove a sheet, or import sheets that were retrieved, using the Pocket PC application.
A lot of the issues that we had to deal with for the survey profile form are the same issues we have to deal with on the run editor form. Listing 3.12 shows one of the most complex routines that support the run editor, adding the run itself to the repository.
Listing 3.12 SurveyV1\SurveyStudio\frmRunEditor.cs Adding a Run to Survey Repository
private void menuItem7_Click(object sender, System.EventArgs e) { // add run to repository frmRepositoryProfileList profList = new frmRepositoryProfileList(); profList.LoadProfiles(); if (profList.ShowDialog() == DialogResult.OK) { int selProfileId = profList.SelectedProfileId; int selRevisionId = profList.SelectedRevisionId; string xmlSource = RepositoryClient.GetProfileRevision( selProfileId, selRevisionId ); DataSet tmpDs = new DataSet(); tmpDs.ReadXml( new System.IO.StringReader( xmlSource) ); DataSet tmpDs2 = new DataSet(); tmpDs2.ReadXml( new System.IO.StringReader( tmpDs.Tables[0].Rows[0]["XMLSource"].ToString() ) ); string existingSurveyId = tmpDs2.Tables["Profile"].Rows[0]["GlobalID"].ToString(); tmpDs.Dispose(); tmpDs2.Dispose(); if (existingSurveyId != this.surveyRun.RunDataItems[0].SurveyID) { MessageBox.Show(this, "You cannot add this run to this Survey Profile, the Surveys are not the same."); } else { frmRepositoryAddRun repAdd = new frmRepositoryAddRun(); repAdd.ProfileLabel = this.surveyTitle; repAdd.ShortDescription = string.Empty; repAdd.LongDescription = string.Empty; if (repAdd.ShowDialog() == DialogResult.OK) { managed_runId = RepositoryClient.AddRun( selProfileId, selRevisionId, repAdd.ShortDescription, repAdd.LongDescription, surveyRun.GetXml() ); managed = true; MessageBox.Show(this, "Current run added to repository", "Repository", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } }
When the user chooses to add the run to the repository, he or she is prompted with a dialog that contains a list of all the profiles and revisions to which that user has access. When a profile and a revision are chosen, that survey profile has to be loaded so that the global ID (a GUID) can be examined. The global ID of the survey is compared with the ID of the survey against which the run was taken. If they don't match, the run cannot be added to that profile in Survey Repository. This is another measure to make sure that data remains consistent.
If the survey destination chosen from Survey Repository does in fact match the survey profile against which the run was taken, the RepositoryClient class (which you'll see a little later in this chapter) is invoked to communicate with the Web service to add the run to the database. After the run has been added to the database, various internal state variables (for example, managed, managed_runId) are modified so that the form behaves like a form that is editing a repository-managed run.
Repository and Disk Storage
Whether the survey runs or profiles are being stored in the repository or on disk, they are stored in XML format. The XML format is actually dictated by the typed data sets that were built to allow for easy programmatic access to survey information.
Figure 3.4 shows the typed data set for a survey profile, in the XSD designer view. (Showing the XSD in XML view is not only lengthy and painful but makes it much harder to view relationships.)
Figure 3.4 The SurveyProfile typed data set (relational view).
Figure 3.5 shows the data structure for the survey run.
These two data structures are used in multiple places throughout the Survey Development Suite. The Windows Forms application makes the most direct use of them, although their XML formats are stored in string form in the database through the Web service.
Figure 3.5 The SurveyRun typed data set (relational view).
Code Tour: The RepositoryClient Class
RepositoryClient is a class with static methods and variables that I created to function as a global wrapper for the method calls to the Web service. The reason I did this was to abstract the action of calling the Web service so that if I wanted to build in layers of detail later, I wouldn't have to modify all my GUI codejust the RepositoryClient class.
In addition to wrapping all the methods exposed by the Web service, the RepositoryClient class keeps track of the current user's credentials and his or her authorization token so that each time a Windows Forms application needs to make a call, it doesn't need to keep track of that information. Listing 3.13 shows the RepositoryClient class.
Listing 3.13 SurveyV1\SurveyStudio\RepositoryClient.cs The RepositoryClient Class
using System; using System.Timers; using System.Data; using System.Text; using System.IO; namespace SAMS.Survey.Studio { public class RepositoryClient { private static repositoryLogin.Login loginService; private static repositoryMain.RepositoryService repositoryService; private static string userToken; private static System.Timers.Timer reloginTimer; private static RepositoryClient singletonInstance; private static string clientUserName; private static string clientPassword; private static bool loggedIn; public delegate void LoginDelegate(string userName, string password); public static event LoginDelegate OnLogin; static RepositoryClient() { loggedIn = false; loginService = new repositoryLogin.Login(); repositoryService = new repositoryMain.RepositoryService(); singletonInstance = new RepositoryClient(); } public static void Login(string userName, string password) { clientUserName = userName; clientPassword = password; PerformLogin(); reloginTimer = new Timer(3600000); // every hour reloginTimer.AutoReset = true; reloginTimer.Elapsed += new ElapsedEventHandler( OnTimerElapsed ); reloginTimer.Start(); } public static void LogOff() { reloginTimer.Stop(); loggedIn = false; } private static void OnTimerElapsed(object sender, ElapsedEventArgs e ) { PerformLogin(); } public static string GetProfile( int profileId ) { string xmlProfile = repositoryService.GetProfile( userToken, profileId ); return xmlProfile; } public static string GetProfileRevision( int profileId, int revisionId ) { return repositoryService.GetProfileRevision( userToken, profileId, revisionId ); } public static int CheckInProfile( int profileId, string revisionComment, string xmlSource ) { return repositoryService.CheckInProfile( userToken, profileId, revisionComment, xmlSource ); } public static int CreateProfile( string shortDescription, string longDescription, bool isPrivate, string xmlSource) { return repositoryService.CreateProfile( userToken, shortDescription, longDescription, isPrivate, xmlSource ); } public static DataSet GetUserProfiles() { string xmlProfiles = repositoryService.GetUserProfiles( userToken ); DataSet ds = new DataSet(); StringReader sr = new StringReader( xmlProfiles ); ds.ReadXml( sr ); return ds; } public static DataSet GetProfileRuns( int profileId ) { string xmlRuns = repositoryService.GetProfileRuns( userToken, profileId ); DataSet ds = new DataSet(); StringReader sr = new StringReader( xmlRuns ); ds.ReadXml( sr ); return ds; } public static DataSet GetRun( int runId ) { string xmlRun = repositoryService.GetRun( userToken, runId ); DataSet ds = new DataSet(); StringReader sr = new StringReader( xmlRun ); ds.ReadXml( sr ); return ds; } public static DataSet GetAllRevisions() { string xmlRevisions = repositoryService.GetAllRevisions( userToken ); DataSet ds = new DataSet(); StringReader sr = new StringReader( xmlRevisions ); ds.ReadXml( sr ); return ds; } public static int GetProfileStatus( int profileId ) { return repositoryService.GetProfileStatus( userToken, profileId ); } public static int AddRun( int profileId, int revisionId, string shortDescription, string longDescription, string xmlSource ) { return repositoryService.AddRun( userToken, profileId, revisionId, shortDescription, longDescription, xmlSource ); } private static void PerformLogin() { userToken = loginService.LoginUser(clientUserName, clientPassword); if (userToken != string.Empty) loggedIn = true; else loggedIn = false; if (OnLogin != null) { OnLogin( clientUserName, clientPassword ); } } public static string UserToken { get { return userToken; } } public static string CurrentUser { get { if (loggedIn) return clientUserName; else return string.Empty; } } public static bool LoggedIn { get { return loggedIn; } } } }
The first thing to point out about this class is that right at the top of the class definition, we can see the declaration for an event handler:
public delegate void LoginDelegate(string userName, string password); public static event LoginDelegate OnLogin;
This event handler allows the Windows Forms application to respond to a successful login without blocking the execution of the foreground thread. Having this class expose the event handler like this makes it very easy for the application to respond to events triggered by the Web service. One thing you might notice is that this particular structure may also lend itself quite well to allowing this class to be converted in such a way that all access to the Web service can be made asynchronously so as not to block the application during network activity.
Another interesting piece of this class is the use of a re-login timer. One thing you may have noticed while browsing the code for the Survey Repository Web service is that when authorization tokens are added to the application cache, they are added with a sliding expiration time period of one hour. This is to ensure the security of the system. If, for some reason, someone has been sniffing packets and manages to peel an authorization token out of one of those packets, that token will be valid for only a short period of time. When the token has expired, any hijacked-token messages fail when the service attempts to establish a user identity.