SharePoint Quick Surveys
I thought I’d publish a little web part I’ve been working on which allows users to quickly fill in a survey from a site page and see attractive graphical results in place. The idea of course is to push important survey questions to the user’s home page- perhaps in the right hand bar- rather than making them go to the survey list page to submit a response.
The control can be hosted on any web part page and can accept responses for any survey within the same site. The first time the user sees the web part they will be prompted to fill in their responses to the survey. Once they have done this the display will change to show the results in a series of graphics. All questions in the survey will be displayed, so it is probably a good idea to keep the survey short if you want to place it on the home page of your site.
|
|
If the survey allows multiple responses then a link will be displayed along with the results which allows the user to submit further responses. Otherwise they will only be allowed to post one response.
Configuration of the web part is simple too. Aside from the usual properties there are two new sections allowing selection of a survey list and configuration of the survey results display.
The control can display it’s results graphs horizontally or vertically. You should set this property depending on what what part zone is being used. Vertical works best on the side bar whilst horizontal is better in other zones. You can also select whether bar charts or pie charts are used for displaying the results of questions (except for grid choice questions which always use bar charts due to their more complex nature).
|
|
You can also choose to use the control just to display results of surveys. In this case tick the “show results only” check box in the tool pane. The results of the survey will then be displayed straight away and regardless of whether the current user has submitted a response or not.
A setup kit and the full c# source code for this project are provided in the downloads section. To install the web part simply run the setup kit and then activate the newly installed site collection feature. This will result in the web part becoming available in the web part gallery.
Technical Notes
The web part is essentially a composite control with two views: survey response and results display. The survey response display is where the user enters their answers to the survey questions. This functionality is provided by SharePoint out of the box in the form of the SurveyFieldIterator control. We simply point this at the survey list in question and it does the heavy lifting of displaying the survey questions.
surveyControl = new SurveyFieldIterator(); surveyControl.ListId = theList.ID; surveyControl.ControlMode = SPControlMode.New;
We add a submit button to this control and we’re set. When the user clicks the submit button we store their responses in the survey list. This is a simply process of saving a list item which is provided to us by the SurveyFieldIterator control. It is important to remember to validate the page at this point as RequiredFieldValidator controls will have been added to the page for any mandatory survey questions.
void btnSubmit_Click(object sender, EventArgs e)
{
EnsureChildControls();
Page.Validate();
if (Page.IsValid)
{
try
{
surveyControl.ListItem.Update();
surveyControl.Visible = false;
btnSubmit.Visible = false;
results.ResetCache = true; // Reset the cache when a response is submitted
results.Visible = true;
multiResponsePane.Visible = theList.AllowMultiResponses && !ResultsOnly;
}
catch (Exception ex)
{
lblMessage.Text = Properties.Resources.msg_submiterror + ": " + ex.Message;
}
}
}
Once the user has submitted their responses we switch to results mode. This means hiding the response control and displaying an instance of the SurveyResultsIterator control which is a custom control designed to display the survey results. SurveyResultsIterator inherits from the built in ListFieldIterator which contains a very handy function IsFieldExcluded which we can use to determine if an individual field in the survey is to be displayed in the survey results. For each such field we generate an html image tag which gets an image from a handler installed by the feature- SurveyResultsHandler.ashx.
class SurveyResultsIterator : ListFieldIterator
{
string handlerUrl = "/_layouts/darrenjohnstone.net.QuickSurvey/SurveyResults.ashx";
/// <summary>
/// Gets/sets a boolean value indicating if the cache should be reset.
/// </summary>
public bool ResetCache
{
get;
set;
}
/// <summary>
/// Gets/sets the type of chart to draw for non-rating questions.
/// </summary>
public ChartType ChartType
{
get;
set;
}
/// <summary>
/// Gets/sets the type of chart to draw for non-rating questions.
/// </summary>
public ChartAlignment ChartAlignment
{
get;
set;
}
/// <summary>
/// Constructor.
/// </summary>
public SurveyResultsIterator()
: base()
{
ControlMode = SPControlMode.Display;
}
/// <summary>
/// Creates the child controls.
/// </summary>
protected override void CreateChildControls()
{
}
/// <summary>
/// Renders the specified output.
/// </summary>
/// <param name="output">The output.</param>
protected override void Render(HtmlTextWriter output)
{
output.Write("<table>");
int questionNumber = 1;
output.Write("<tr>");
for (int i = 0; i < Fields.Count; i++)
{
if (!IsFieldExcluded(Fields[i]))
{
if (ChartAlignment == ChartAlignment.Vertical && questionNumber > 1)
{
output.Write("<tr>");
}
output.Write("<td valign='top'>");
output.Write("<table>");
output.Write("<tr>");
output.Write("<td>");
output.Write(String.Format("<b>{0}. {1}</b>", questionNumber.ToString(), Fields[i].Title));
output.Write("</td>");
output.Write("</tr>");
output.Write("<tr>");
output.Write("<td>");
output.Write("<img src='{0}?site={1}&survey={2}&field={3}&type={4}&time={5}&nocache={6}'/>",
handlerUrl,
HttpContext.Current.Server.UrlEncode(List.ParentWeb.ServerRelativeUrl),
HttpContext.Current.Server.UrlEncode(List.Title),
i.ToString(),
ChartType == ChartType.Pie ? "pie" : "bar",
DateTime.Now.Ticks.ToString(),
ResetCache ? "yes" : "no");
output.Write("</td>");
output.Write("</tr>");
output.Write("</table>");
output.Write("</td>");
if (ChartAlignment == ChartAlignment.Vertical && questionNumber > 1)
{
output.Write("</tr>");
}
questionNumber++;
}
}
output.Write("</tr>");
output.Write("</table>");
}
}
The SurveyResultsHandler class is an HTTP handler which returns a PNG image for a given survey question. This handler is responsible for collating results from the survey and using GDI+ to draw an appropriate results graph. The handler accepts a series of request parameters which determine the list, field, and graph type it uses to generate results. Once a reference to the appropriate field is established, the results are collated and a graph draw. The handler can generate bar charts and pie charts for all survey questions but the grid choice type. For these it generates a specific type of bar chart.
A simple caching mechanism is used to ensure that graphs are not drawn unless required. Each time a new response is gathered for the survey the cache is reset by appending a resetcache=yes variable to the SurveyResultsHandler.ashx request.
bool RespondFromCache()
{
string key = CacheKey();
if (HttpContext.Current.Cache[key] != null)
{
Image img = HttpContext.Current.Cache[key] as Image;
if (img != null)
{
using (MemoryStream stream = new MemoryStream())
{
img.Save(stream, ImageFormat.Png);
stream.WriteTo(HttpContext.Current.Response.OutputStream);
return true;
}
}
}
return false;
}
void SetCache(Image img)
{
string key = CacheKey();
HttpContext.Current.Cache.Add(key, img, null, DateTime.Now.AddMinutes(10), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
}
From then on, each time the control is displayed it checks to see if the current user has already responded. If so then the results are automatically displayed.
bool AlreadyResponded()
{
SPQuery query = new SPQuery();
query.Query = String.Format("<Where><Eq><FieldRef Name='Author'/><Value>{0}</Value></Eq></Where>", SPContext.Current.Web.CurrentUser.LoginName);
return (theList.GetItems(query).Count > 0);
}
This control could easily be extended to use SilverLight to display survey results instead of GDI+. The principles are the same- we’d just return XAML instead of PNG images. A task for another day though!

Comment by Banker on 5 June 2008:
Darren,
Thanks a lot for your webpart. It is really the one I have been looking since the first relase of SPS. For some reason the images are not shown on a different site collection other than the default one.
For example part of the default url for image is “…SurveyResults.ashx?site=%2f&survey=…” but if url is “…SurveyResults.ashx?site=%2fsites%2fTest&survey=…” the image is not showing up.
Any pointers please.
Comment by darren on 6 June 2008:
Banker,
Have you updated to version 1.0.1 (get it in the downloads section). This was a known bug that was fixed in that release. If you have updated please send me the full URL of the image which does not display and I will try to help you more.
Darren
Comment by Banker on 6 June 2008:
Darren,
Thanks a lot. The release 1.1 solves this issue. Really a very great web part.
Comment by Raymond on 12 June 2008:
Darren,
i was wondering if and how i could translate this webpart to Norwegian?
Comment by darren on 14 June 2008:
Hi Raymond,
Sure. It would be great to get the webpart translated. To do this you can create a new resource file in the source code download. You will see that resources.resx contains a list of English phrases. You need to create a new file (resources.no.resx) with the same keys and the translated phrases. If you do this please send me the file and I’ll make a new release for the rest of the community.
Thanks
Comment by Saroj Jha on 15 August 2008:
Hi Darren,
Really a nice WebPart.
I needed to filter few question in Graphical result.
As well as try to give a shot to display the Results for on Monthly basis.
Without the help of the your WebPart i couldn’t have thought of doing all this.
Saroj jha
Comment by Max on 21 August 2008:
Hi Darren,
I installed your WebPart on all web applications successfully.
But I can’t add on the page your WebPart! I can’t find it in the WebPart list for add. Please, help me!!! I need to view survey on Portal Page.
Comment by darren on 21 August 2008:
Hi Max,
The WebPart is installed as part of a feature. It will only appear once the feature is activated. Go to site actions -> site settings -> site collection features and check that the Quick Surveys feature is activated by clicking the activate button.
Cheers,
Darren
Comment by Max on 22 August 2008:
Hi Darren,
Thank you for replay.
I do this. Now I can add your WebPart to my Portal Page.
But then I add WebPart to my Portal Page all users with Visitor (users which can view pages and ) role can’t see this page (Error: Access Denied)! Then I close WebPart my users again view my page…
Comment by darren on 22 August 2008:
Hi Max,
Can you make sure that the visitors have permissions to post responses to the survey that you’ve created?
Cheers,
Darren
Comment by Max on 25 August 2008:
Hi Darren,
Ok. I give right to post responses to the survey and my users can now to see the Portal Page (unfortunately I don’t want to give right to post responses because I need to add your WebPart only in “Show results only- do not allow responses” mode, but it is not such important now).
Darren, I add new Summary Link Web Part with link for response survey “Response” (on my original language;)), but then user complete survey the WebPart on the Portal Page don’t changed, even after refresh or reopen page, but after some minutes the WebPart was changed… It is normal?
Comment by darren on 25 August 2008:
Hi Max,
The results are cached for a few minutes. They are reset after a user fills in the survey. This is normal behaviour to prevent the graphs from being redrawn too frequently. In the next release I will provide some properties allowing the cache duration to be controlled.
Cheers,
Darren
Comment by Max on 26 August 2008:
Darren, thank you for you responses and work.
I send you “resources.ru.resx” for a new release for russian!
Comment by darren on 27 August 2008:
Hi Max,
Thanks for this. I’ll add it in and make a new release soon.
Cheers,
Darren
Comment by Rehmo on 3 September 2008:
Hi Darren,
I used WSS 2003 is it compatible?
Comment by darren on 3 September 2008:
Rehmo- no, unfortunately not. This is for WSS 3.0 and MOSS 2007 only.
Cheers,
Darren
Comment by Sian Doherty on 8 September 2008:
I notice that in your surveys your text is aligned to the left. Can you tell me how to do that. I have created a very basic survey and it just looks like rubbish because the text is automatically aligned to the right so it just looks very unprofessional, however i can not find anywhere to align the text to the left in the survey itself?
Thanks
Comment by darren on 8 September 2008:
Hi Sian,
The text is aligned to the left by default. I just tried this on a blank WSS installation to confirm- all left aligned out of the box. Perhaps you have a custom theme which is affecting it?
Cheers,
Darren
Comment by Rehmo on 12 September 2008:
Hi Darren,
Thanks, regarding access denied (if i remove quick survey no problem), i want my users to have access only on Survey web part.
Comment by darren on 14 September 2008:
Hi Rehmo,
You need to check that your users have permissions on the survey list you are binding to. They need to be able to read the results so that the control can check if they have submitted a response before and collate the results for the graphs. Give your users permissions and try again.
On a side note, if it is a problem giving users permissions then the control could be used in results only mode with permissions being elevated in the code using
SPSecurity.RunWithElevatedPrivileges. I might make this an option in a later version if people ask for it.Cheers,
Darren
Comment by cloudno9 on 16 September 2008:
Hi Darren,
once i submit the survey questions and see the graph. Next time when i log back in I see the questions again although I have answered them already, shouldnt i be seeing the results instead of questions? and if i submitt again it tells me that I have already submitted this survey but still dont show my any graph.
ciao
Comment by darren on 17 September 2008:
cloudno9- what version of the control are you using? Is it the latest 1.0.3? This sounds like a bug that was fixed a while ago.
Cheers,
Darren
Comment by Mark on 18 September 2008:
Darren, sweet web part. I am using 1.0.3, if I don’t have the latest please direct me. I’m getting the same thing as cloudno9 when connecting externally. Using the internal server mapping it works fine.
Comment by darren on 18 September 2008:
Hi Mark,
How are your external users authenticated? Is it anonymous access, forms authentication, or NTLM. Let me know and I’ll look into it for you. Personally, I only use the control on intranets with AD authenticated users but I’m happy to test it out externally and make any changes needed for the next version.
Cheers,
Darren
Comment by Mark on 18 September 2008:
You are quick with the responses. Thank you. I have an extended web app providing forms authentication.
Comment by Mark on 23 September 2008:
Darren, I went in again on the intranet side this time (NTLM) and the graph is gone. I guess I am having the same issue as cloudno9. I also tried uninstalling and re-installing. Feel free to email me if there is anything you want me to test.
Thanks
Comment by darren on 23 September 2008:
Hi Mark,
I’ve sent you an updated setup kit to try. If you can try it out and let me know if it fixes your issue that would be great.
Cheers,
Darren
Comment by cloudno9 on 23 September 2008:
can you email me the latest bits also? at cloudno009@hotmail.com
Comment by Krishan on 20 October 2008:
Hi Darren
Indeed a very useful web part. But when we use it with surveys that have branching, there are a couple of problems. By default, Sharepoint inserts a page break at the point of branching and so we can a submit after first question itself and for this webpart as we press the Submit button, it takes us to the Result mode
Besides that, its a cool webpart.
-Krishan
Comment by darren on 20 October 2008:
Hi Krishan,
Yes, you are correct. Branching is not supported. The intention is to only display simple surveys usually with only one or two questions- more complex surveys with branching should use the inbuilt SharePoint display.
Cheers,
Darren
Comment by steven on 5 November 2008:
Thanks for your quick survey webpart, I like it very much, however, can you give me some tips to change this into a quiz web part
Comment by Carsten on 10 November 2008:
How do I create a survey that displays Radio Button’s for one question horizontal and not vertical how it is displayed in picture 1?
Comment by Ton Walter ZERMEÑO VALENCIA on 22 November 2008:
Dear Darren,
We love your Quick survey. However, some of our site users have complained that the poll is commanding the landing page’s focus. Provided the component is placed lower down in our homepage, users find it weird that the site’s designed header and menu are not visible upon first access to the page, until they answer the survey. How can we keep the Quick survey component from commanding focus? Thanks in advance for your kind support. Regards.
Comment by Nik on 27 November 2008:
This looks great, it’s exactly what I’ve been looking for. I like they way it uses the standard survey components.
I do however seem to have the problem with it not detecting that the user has already completed a survey. I’m running 1.0.4 in a MOSS intranet environment with only windows authentication enabled. I only see the survey results immediately after clicking submit. If I refresh the page I get the questions again.
Any ideas?
I’m busy installing VS2008 so I can have a go at debugging it, but I’m no SharePoint programmer so any help would be appreciated.
Cheers
Nik
Comment by Barry Verkaik on 27 November 2008:
Is there a way to change the resource file (I want to change the translation of some lines) without having to recompile the solution?
Comment by Mehul Bhuva on 1 December 2008:
Hi Darren,
I am a regular follower of your blog. i love your articles. Please keep up the good work of sharing knowledge.
I am pretty impressed by the survey webpart, but there is an issue which Cloud009 and Mark has already raised.i.e When you log back in after participating in the survey, it still shows you the Questions and the Options instead of showing results, I am using AD authentication on a publishing portal and have downloaded the latest v1.0.4 of Survey webpart.
Can you send me the solution, you have already shared with Cloud009 and Mark.
Thanking you in anticipation..
Comment by Mehul Bhuva on 1 December 2008:
Hi Darren,
I want to maintain a single list on the Top level sitecollection. So this Survey webpart can be used across all the sites in a site collection, but it will get survey questions only from a single list.
How can i achieve this ? Where all do i need to modify your source code.. Presently I tried using SPContext.Current.Site.RootWeb wherever required and it is working only for the Top Level site, but for sub-sites it is not working and gives an error message.
Comment by Drasko Popovic on 2 December 2008:
Have You tried Quick Survey with Windows Server 2008 and MOSS 2007 sp1? I tried to install but it keeps saying that timer Service is not started. I checked the Central Administration and Services tool and everything is OK.
Any Idea?
Comment by Greg McAllister on 10 December 2008:
Darren,
I need to be able to eliminate Text field types from the results. Can this be done in the source code? If so, could you give a hint? Secondly, which version of VS can the source be edited in?
Thanks!
Greg
Comment by Eric on 4 February 2009:
Hi Darren,
Great web part!! Is there a way to limit the total number of responders to the survey? Meaning, only the first 50 people can fill out the suvey?
Comment by LN on 9 February 2009:
Hi and thanks for a great web part!
For those who wants the web part to detect if the survey is already answered or not, find the following line in quicksurvey.cs (line 129):
author = SPContext.Current.Web.CurrentUser.LoginName;
change to
author = SPContext.Current.Web.CurrentUser.Name;
Recompile the solution.
/LN
Comment by darren on 15 February 2009:
Cheers for this LN!
Comment by darren on 15 February 2009:
Hi Eric, see here http://darrenjohnstone.net/2009/02/15/sharepoint-quick-surveys-105-and-catching-up/. Cheers
Comment by Sohail on 18 February 2009:
hi Darren, Great web part! I have the same question as Carsten asked above!
How do I create a survey that displays Radio Button’s for one question horizontal and not vertical how it is displayed in picture 1?
I am using WSS 3.0 Thanks, Sohail
Comment by Sohail on 18 February 2009:
Sorry please ignore my previous post. I managed to do it. In case it might help someone:
Survey Library ==> Add Question
Select the Question Type: Rating Scale (a matrix of choices or a Likert scale)
Sohail