Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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 that—nothing 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.4Figure 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.5Figure 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 code—just 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.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020