Friday, February 13, 2009
Correction - Customized Input Forms: The JavaScript Approach
If a user is modifying a list item, and they have disabled controls on the page (grayed out), then when they save the item, those disabled fields will revert to the default value specified for each of those columns. The correct values populate on the page, but apparently the values stored within disabled controls do not get returned to the server upon the form being submitted.
I have come up with a quick solution (not sure if it is the best at this moment), but it allows for the values to be returned to the server by re-enabling all of the disabled fields just before the form is submitted. Only problem so far is that if the page takes a while to submit, the fields appear to be editable to the user, even though changes made won't actually be sent to the server.
Please see this link for a reference to the function PreSaveAction(): Add JavaScript Date Validation into List Item forms
Updated code (new code added is highlighted in yellow): CustomizedInputForms_JavaScriptFile
Enjoy!
--andrew
MOSS Cascading DropDownLists - The Sexy Approach - 2 of 2
Link to previous post: MOSS Cascading DropDownLists - The Sexy Approach - 1 of 2
Welcome to the second half of my discussion about AJAX Cascading DropDownLists within SharePoint 2007. I apologize for not getting this posted earlier, but I've been swamped at work lately. There is a lot of code involved, and I would like to thank the following people for various bits and pieces which I borrowed (links to my code are at the bottom of the post):
- Todd Bleeker: Custom Field Control discussion at SharePoint Best Practice Conference 2007
an extremely informative and helpful introduction to the various components of a custom field control - DataCogs: Sharepoint – Cascading Drop Down Lists
an excellent example of a custom field control, especially one solving the same problem I was looking to solve - Wouter van Vugt: Creating a Windows SharePoint Services 3.0 Custom Field by Using the EntityPicker
an excellent explanation of the problems associated with saving a new field control instance for the first time, and how to correctly save the properties.
As the manifest.xml and wsp_structure.ddf files are pretty straightforward if you've worked with SharePoint Solution packages before, I will not discuss these.
Here is a great walkthrough on the different elements required in creating a custom field type on MSDN: Walkthrough: Creating a Custom Field Type.
We'll start with the creation of the field type definition: fldtypes_cascadingdropdownlist.xml. This file is used to store the various configuration information related to your custom field type. Multiple field types can be defined within the same file, however, this is not advised. All of the fields at the top are standard custom field type definition attributes.
- TypeName is the internal name for this field type
- TypeDisplayName is what will be displayed on the "Create a new column" page
- FieldTypeClass is where you reference the assembly containing your field type class
- FieldEditorUserControl is the location of the ASCX file which defines the user interface for Custom Properties
- PropertySchema is used to define custom properties.
All of my custom properties are simple TEXT fields, which have fixed length and are hidden. This is so I can use other controls (like DropDownLists) for the creation of the column, to make selecting values easier on the user. These custom properties are where I store which list supplies the data and how it is displayed/filtered.
- RenderPattern is not used in my solution.
The class and assembly referenced in the attribute FieldTypeClass is used as the base class for storing/retrieving custom and default properties for this field type. Please see the comments in CascadingDropDownList.cs for a more detailed breakdown of functionality. I have opted to use the ThreadData method for storing values on initial column creation as mentioned previously in the MSDN article by Wouter van Vugt.
In CascadingDropDownList.cs near the bottom, I am using the custom class CascadingDropDownListEditControl as the RenderingControl. The user control for this is incredibly simple: CascadingDropDownListEditControl.ascx. It is just a normal DropDownList inside of a SharePoint RenderingTemplate. The class file associated with this ASCX file is CascadingDropDownListEditControl.cs. There are a few key components of this class to note:
- ddlCascading.ContextKey is used to pass the necessary information to access a SharePoint list to the Web Service which will be populating the DropDownLists on the client side.
- ddlCascading.ParentControlID has to be set at runtime, as this is the ID of the control on the page, not the value stored within the column's properties.
- Render method is overridden to circumvent the necessity of disabling EventValidation for the CascadingDropDown extender to function. This method obtains all possible values from the corresponding SharePoint lists, and registers them for event validation on the client side (potential performance hit if you have significantly large value lists).
- ddlCascading.ServicePath is the location for the web service to pass the AJAX request to and ddlCascading.ServiceMethod is the method invoked within the given Web Service.
This web service is defined within the files CascadingWebService.asmx and CascadingWebService.cs. The ASMX file is very simple, with just a reference to the assembly containing the web service class. Within the class, there are two functions: GetListItemsPageMethod and SortNameValuePair. The name for GetListItemsPageMethod can vary as long as it is the same here as it is in CascadingDropDownListEditControl.cs for ddlCascading.ServiceMethod. However, the *signature* for this method must be exactly as displayed. The contextKey at the end is optional (if you don't have to supply additional information for the AJAX request), but the rest of the parameters, as well as the security modifier and return type must be the same as I've used. SortNameValuePair, on the other hand, is a custom function I created to allow for sorting the collection of CascadingDropDownNameValues, since List.Sort does not know how the name-value pairs should be compared.
And the final component to this solution is the Properties class for the Cascading DropDownList. The Properties class is used for defining the way in which custom list properties (specified within the field type definition fldtypes_cascadingdropdownlist.xml) are displayed on the column creation/modification page. Again, please reference the comments within CascadingDropDownListPropControl.cs for a description of what is happening. It displays and modifies the custom column properties (which are defined as TEXT elements) using a Text Box, a Button, and several DropDownLists. CascadingDropDownListPropControl.ascx is a little more involved than the other ASCX files, but much of the HTML was simply to ensure that the properties for this custom field control looked like the properties for out-of-the-box field controls.
For the Name/Value columns, the source SharePoint list needs to be established as follows:
- For each Cascading DropDownList you plan to have, you need a column to represent its potential values.
- Be sure to enter all possible values for Parent, Child, Grandchild, etc within each list item
- Here is a picture of my sample list: Bird Classifications
I tried to supply a lot of code, with the hope that it would be self-explanatory. If you need further explanation of what is happening, or why I did it this way, please do not hesitate to comment below. Here are some pictures of a sample implementation for Bird Sightings, using 3 Cascading DropDownLists (Family[Parent] -> Genus[Child] -> Species[Grandchild]):
- Creating the Family Column - Entering a URL
- Creating the Family Column - Choosing the SharePoint List which supplies values
- Creating the Family Column - After DropDownLists are populated
- Creating the Family Column - Selecting columns which provide text/values
- Creating the Family Column - No Parent Fields Available
- Creating the Family Column - Sorting Options
- Creating the Genus Column - Choosing a Filter Column
- Creating the Genus Column - Choosing a Parent Column
- Creating the Species Column - Choosing a Parent Column
- Entering a List Item - Page Load 1
- Entering a List Item - Page Load 2
- Entering a List Item - Page Load 3
- Entering a List Item - Species Values
- Entering a List Item - Selecting a Different Genus
- Entering a List Item - New Species Values
- Slideshow of multiple DropDownLists in Action
Limitations:
- The Cascading DropDownList controls must be displayed in order on the page, in the order you want their relationship to be (Parent before Child, and Child before Grandchild, etc.) If the Child is before the Parent, then the Child control will not be able to find the Parent control on the page.
- It is possible to modify the Parent field of a Cascading DropDownList to a control which appears lower on the form page. The filtering of values in the "Parent Column" property only removes the current field.
- If you have a Parent->Child->Grandchild relationship, and different Parent values have the same Child values in the source SharePoint list, then all of the potential Grandchildren for each Child will be visible if that Child is selected, regardless of which value is entered into Parent.
This control has already received widespread use within my organization. If you have any recommendations on improvement to remove these limitations, I would love to hear about the modifications you have made to the below code. I hope you enjoyed this deep-dive into employing the AjaxControlToolkit's CascadingDropDown within SharePoint using a Custom Field Control.
Enjoy!
--andrew
Links to solution files:
Tuesday, December 9, 2008
MOSS Cascading DropDownLists - The Sexy Approach - 1 of 2
Link to next post: MOSS Cascading DropDownLists - The Sexy Approach - 2 of 2
I am really excited about this post for a number of reasons:
- AJAX makes things look really slick
- Cascading DropDownLists in SharePoint are a pain
- I've finally finished this project!
- Data Cogs - SharePoint Cascading Drop Down Lists
- MSDN - Creating a Windows SharePoint Services 3.0 Custom Field by Using the EntityPicker
- Mike Ammerlaan - Integrating ASP.NET AJAX with SharePoint
- Rich Finn - Ajaxify MOSS
- You must have .NET Framework 3.5 SP1 installed on your server
- You must add the AjaxControlToolkit DLL to your VS solution
--andrew
Friday, December 5, 2008
.Net Framework 3.5 SP1 and SharePoint Search/InfoPath/Etc.
- Administrator approved InfoPath forms with custom code were causing errors (no indication of what the error was)
- Search Service was failing to crawl content with the error "Access Denied."
Enjoy!
Monday, July 28, 2008
Customized Input Forms: The JavaScript Approach
If any of you have had to customize the input forms for lists or libraries in SharePoint, you'll know that it is not easy. You can customize the form with a custom list form web part, but you better not delete the original list form web part, otherwise your list gets hosed. You can have both on the page (with the original web part hidden), but then you lose attachment support with JavaScript errors. If you create a new page without the original list form web part, then you get a nice JavaScript alert saying that the form has been customized to not allow attachments. If you used the custom list form web part, then you might find it cumbersome and tedious to make changes when new columns are added. I have tried countless recommendations for modifying the list input form, and none of them really seemed to work cleanly and effectively. Until I stumbled across the forum discussion located here on MSDN Forums.
Of all of the ideas proposed in this forum topic, I found tscheifler's usage of JavaScript quite intriguing. There were some limitations that I found when implementing their exact solution (most notably around disabling columns of type: Lookup, Date and Time, and Multiple lines of Text). Extending this, and incorporating various other bits of information lying about the web, I ended up with a solution I am quite happy with. This assumes you have an existing list with several fields you would like to hide/disable for certain user groups. We will begin by modifying the "NewForm.aspx" page, but these steps will work for any of the input forms:
- Open the "New Form" for the list and remove all query string variables (should end up with http://server/site/listname/NewForm.aspx)
- Append "?ToolPaneView=2" onto the end of the url (http://server/site/listname/NewForm.aspx?ToolPaneView=2)
Note: this places the page into "Add a Web Part" view - Add a new "Content Editor Web Part"(CEWP) to the page after the existing web part
- Modify the source view of the CEWP to include this code:
<SCRIPT LANGUAGE="JavaScript"> <!-- function disableChildren(currentElement) { if (currentElement) { if(currentElement.tagName == "IFRAME") { frm = window.frames[currentElement.id].document; disableChildren(frm.getElementsByTagName("html")[0]); } var i=0; var currentElementChild=currentElement.childNodes[i]; while (currentElementChild) { disableChildren(currentElementChild); i++; currentElementChild=currentElement.childNodes[i]; } if (currentElement.tagName) { currentElement.setAttribute("disabled", "true"); currentElement.setAttribute("contentEditable", "false"); currentElement.setAttribute("onclick", ""); currentElement.removeAttribute("href"); } } } function hideRowsAfter(currentRow) { row = currentRow.nextSibling while (row) { row.style.display = "none"; row = row.nextSibling; } } function findControl(FieldName, opp) { FieldName = "FieldName=\"" + FieldName + "\""; //get all comments var arr = document.getElementsByTagName("!"); for (var i=0;i < arr.length; i++ ) { // now match the field name if (arr[i].innerHTML.indexOf(FieldName) >= 0) { switch(opp) { case 0: //disable all children disableChildren(arr[i].parentNode.parentNode); break; case 1: //hide row arr[i].parentNode.parentNode.style.display="none"; break; case 2: //hide all rows after current hideRowsAfter(arr[i].parentNode.parentNode); break; default: break; } } } } function disableControls(inputArray) { for (var i=0; i < inputArray.length; i++) { findControl(inputArray[i], 0); } } function hideControls(inputArray) { for (var i=0; i < inputArray.length; i++) { findControl(inputArray[i], 1); } } function hideControlsAfter(input) { findControl(input, 2); } //Usage: // disableControls(["Field Name 1", "Field Name 2"..]); // hideControls(["Field Name 1", "Field Name 2"..]); // hideControlsAfter("Field Name"); //--> </SCRIPT> - Follow the "Usage notes" to add calls to the disableControls, hideControls, or hideControlsAfter functions which will modify the fields displayed on the page
Note: you can find the values to put in place of "Field Name 1" and "Field Name 2" by viewing the source view for the page and searching for: FieldName="
The value within the double quotation marks will be what you enter inside the arrays in the hide/disable function calls. - In the CEWP's tool pane, add security groups or audiences which should have the fields hidden/disabled to the "Target Audience" setting
- Save the web part properties, and click the "Exit Edit Mode" link in the upper right below "Site Actions".
To extend this into a more reusable solution, I created a custom CEWP with this JavaScript code, exported it to a .dwp file, and then uploaded it to the Web Part gallery. Then, the only modifications needed are to add this web part to the page (under ToolPaneView=2 view), add the "usage" functions, and add the security groups to the targeted audiences.
This solution now hides/disables fields specified within the original list input form, which retains the attachment functionality, while being able to easily make modifications when new fields are added/modified based on column ordering.
However, there are some limitations to this method. None of which were show stoppers for me, since this method is very easy to undo (simply remove the CEWP from the forms). Especially in the interim until Microsoft is able to fix this little problem and offer a clean, efficient, and effective method of customizing input forms. These limitations are:
- Security groups or audiences need to be created for the group of users which should have limited access to list fields, which excludes the users with access to the restricted fields.
- You cannot make any of the hidden/disabled fields required unless you specify default values, as the fields will still remain on the page and submit data, they are just hidden to the user
- If the user employs firebug or other plugins which can alter JavaScript, they could unhide/undisable the fields you removed and then manipulate the data
- Information in these fields is still visible to users if the columns are displayed within list views, as well as Source View of the input form
Enjoy!
--andrew
Thursday, April 10, 2008
Comparing InfoPath Fields - Case Insensitively
- User
- Manager
- Process Owner
- DBA
A problem arose where the Process Owner was actually the user's manager as well, but my rules for determining which view is presented to the user only showed this person the Process Owner view. I did not want to create a new view just for the case of Process Owner == Manager, so I did the following:
- Set the Manager's authorization field to Read/Write on the Process Owner view
- Added a conditional formatting element to the Manager's authorization field to set it to read only when the managerID field does not equal the InfoPath function "userName()"
The resulting expression used in my conditional formatting is (broken onto multiple lines for ease of reading):
translate(
substring-after(
/my:myFields/my:grpEmployeeInformation/my:managerID,
"\"),
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyz") !=
translate(
xdUser:get-UserName(),
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyz")Rather long and cumbersome, but you can see both the left and right hand sides of the "!=" translate all capital letters to their lower case equivalents. The substring-after() bit was just an artifact of the structure of my form, where the managerID field is in the format of "domain\username".
Note: Since this form uses the "userName()" function, it will probably require full trust.
Enjoy!
--andrew
Wednesday, April 2, 2008
DataView Web Parts and Page Layouts
I decided to detach the page from its layout and add the DataView Web Part. Everything seemed to work, except I started to receive errors stating "This Web Part Page has been modified since you opened it." I figured this was related to detaching from the Page Layout (I may have hosed something up unknowingly). I then reattached the page to its layout and everything ended up working fine.
Therefore, if you need to add a DataView Web Part to a page attached to a layout, I suggest doing the following(all done within SharePoint Designer):
- Detach the Page from the Page Layout
- Go through the necessary steps to add a DataView Web Part to an existing zone on the page
- Reattach the Page to it's Page Layout
Note: I have not attempted to reattach a page to a layout after new zones have been added and do not know exactly what will happen.
Enjoy!
--andrew
Wednesday, March 26, 2008
InfoPath Property Promotion Woes
I have been having issues lately with property promotion in InfoPath 2007 forms. When I create, publish, and deploy a form to a SharePoint site, promoted properties function correctly. If I add new structural elements and property promotion settings to a form after it has been deployed to a SharePoint site and is in use in a form library, then the new properties do not appear in SharePoint at all.
This has surfaced as a concern within my company as we have a few forms in use which require structural/property promotion changes. After several days of searching for any information on the capabilities and limitations of property promotion, I stumbled upon the following forum entry: Property Promotion - Full Trust Form - TechNet Forums.
In this forum post, there is some discussion of whether this is a bug or by design and possible resolutions.
Jasbury summed up the thread as:
The workarounds presented in this thread suggest the following:
- Rebuild the library or site
- Replace InfoPath’s “Automatically determine security level” with “Domain Security”
- Deactivate/Reactivate the InfoPath Form Template from the Site Collections
The first suggestion was not an option for my situation.
The second suggestion did not apply to me as I experienced problems with automatic, domain, and full trust permission levels.
The third option, however, was right on the mark. Once I deactivated/reactivated the template, the new properties were promoted successfully.
Thanks to bobchauvin for originally suggesting this:
I also notice when using the Publish to Sharepoint as a content type that a change to the promoted cols wont take effect until you disable and then re-enable the content type for the site collection.
With a little investigation, I discovered what was causing Jasbury's problem here:
I was able to deactivate/reactivate with some success (thanks for this work-around!!!). The missing content type columns were added. However, changes to InfoPath property promotion were not reflected...huge bummer!! That leaves me with no other options that to start over…again!
This is due to the order in which the steps were completed rather than a bug within SharePoint/InfoPath. Field values within an InfoPath form are copied into the corresponding SharePoint columns when the form is saved/submitted. If people have been filling out forms prior to fixing the missing columns in the content type, these values will not be stored anywhere. Once the content type is correct, simply open any forms and save them again for the values to be copied.
I recommend the following order for updating a form which has property promotion/structural changes:
- Deactivate the form from all site collections it is active on
- Upload the new version of the form
- Reactivate the form on all necessary site collections
Enjoy!
--andrew
Thursday, March 20, 2008
Automatic Login with Current User Name and Password....Doesn't
Recently, I had to change my network password at work. This caused a problem which I was struggling to solve: every time I attempted to access the corporate intranet (with the IE setting "Logon automatically with current username/password"), it would prompt me for my password. It worked correctly before my password change, so I figured my password was being cached somewhere.
I attempted to empty the browser cache, restart the machine, relocate the intranet URL to another security zone; all to no avail.
Just today I found a blog post by Nick Porter entitled: SharePoint prompt for password after changing network password. In his post, he states:
Cause:
What seemed to happen was it was storing the old information in the
Password list under the Manage Passwords section under "User Accounts". (Start > Settings > Control Panel > User Accounts)
His resolution was:
1. Click "Start" > "Settings" > "Control Panel"
2. Double click "User Accounts"
3. Click on the "Advanced" tab
4. In the "Passwords and .NET Passports" area click "Manage Passwords"
5. Remove everything there.
Albeit, you do not need to remove *everything* from the managed passwords if other sites are working correctly for you (and you want them to), but I removed the intranet URL, opened a new browser and navigated to the site...and it automatically logged me in!
Thanks Nick Porter.
Enjoy!
--andrew
Wednesday, March 5, 2008
Programmatically Inherit Master Page and CSS in MOSS 2007
- Change the master page and stylesheet settings for a site
- Staple the first feature to all site templates, so it is activated upon site creation
- Becky Bertram - blog - Applying a SharePoint Custom Master page Globally
- Jim Yang - blog - MOSS 2007 and WSS 3.0 Master Page
- Paul Papanek Stork - blog - Feature to Install a Custom Master Page
Brief rundown of SharePoint Object Model:
- SPSite is a Site Collection
- SPWeb is a Site within a Site Collection
- [web_object].MasterUrl
- [web_object].CustomMasterUrl
- [web_object].AlternateCssUrl
Note: all of the following is done within the FeatureActivated function of a custom class inheriting from the SPFeatureReceiver class. Now let's dive into some code (these are all different methods I tried to no avail)
- Created some variables and hard coded the locations within the feature:
string MasterUrl = "/_layouts/custom.master";
string CustomMasterUrl = "/_layouts/custom.master";
string AlternateCssUrl = "/StyleLibrary/Custom/CSS/stylesheet.css";
SPWeb web = (SPWeb)properties.Feature.Parent;
try {
web.MasterUrl = MasterUrl;
web.CustomMasterUrl = CustomMasterUrl;
web.AlternateCssUrl = AlternateCssUrl;
web.Update();
}
catch { } - Set the values of the current site to the values from the root site:
SPWeb web = (SPWeb)properties.Feature.Parent;
try {
web.MasterUrl = web.Site.RootWeb.MasterUrl;
web.CustomMasterUrl = web.Site.RootWeb.CustomMasterUrl;
web.AlternateCssUrl = web.Site.RootWeb.AlternateCssUrl;
web.Update();
}
catch { } - Set the values of the current site to the values from it's parent site:
SPWeb web = (SPWeb)properties.Feature.Parent;
try {
web.MasterUrl = web.ParentWeb.MasterUrl;
web.CustomMasterUrl = web.ParentWeb.CustomMasterUrl;
web.AlternateCssUrl = web.ParentWeb.AlternateCssUrl;
web.Update();
}
catch { }
I decided to take this to the Content Database for the portal in which I was working. Looking in the dbo.Webs table, I found that if the "Inherit" radio button is selected, there are still values in the DB for AlternateCssUrl, MasterUrl, and CustomMasterUrl. Running the above code, would put the same values in these fields, but the "Inherit" radio button would not be selected. I then performed the following steps:
- Copy a row (one site) from the database to a text file
- Change each of the 3 settings (Site Master, System Master, and Alternate CSS) from "Inherit" to "Specify a ..."
- Copy the same row from the database to the second row of the text file
- Change each of the 3 settings back to "Inherit"
- Copy the same row from the database to the third row of the text file
- Change each of the 3 settings back to "Specify a ..."
- Copy the same row from the database to the fourth row of the text file
- "Inherit": 547275
- "Specify a ...": 46616C73
- SPWeb.Properties (C# type SPPropertyBag)
- vti_extenderversion: 12.0.0.4518
- vti_associatevisitorgroup: 4
- vti_defaultlanguage: en-us
- vti_associategroups: 5;4;3;6;7;8;9;10;11;14;15;17;18;28
- vti_associateownergroup: 3
- vti_associatemembergroup: 5
- SPWeb.AllProperties (C# type Hashtable)
- vti_extenderversion: 12.0.0.4518
- __InheritsCustomMasterUrl: False
- vti_associatevisitorgroup: 4
- vti_categories: Business Competition Expense\ Report Goals/Objectives Ideas In\ Process Miscellaneous Planning Schedule Travel VIP Waiting
- vti_associatemembergroup: 5
- vti_defaultlanguage: en-us
- vti_associateownergroup: 3
- vti_associategroups: 5;4;3;6;7;8;9;10;11;14;15;17;18;28
- __InheritsAlternateCssUrl: False
- vti_approvallevels: Approved Rejected Pending\ Review
- __InheritsMasterUrl: False
I simply set these values to "True" (note, that is a string of "True" and not a 1 or C# true), which resulted in this:
However, it did not pull the correct values to begin with. Therefore, it would appear that SharePoint uses these settings for when the parent's master pages/css are changed, and not relying on these settings for everytime the site is accessed.
All in all, here is the final code I came up with for my Feature (inside FeatureActivated function):
SPWeb web = (SPWeb)properties.Feature.Parent;
Hashtable hash = web.AllProperties;
try {
web.MasterUrl = web.ParentWeb.MasterUrl;
hash["__InheritsMasterUrl"] = "True";
web.Update();
}
catch { }
try {
web.CustomMasterUrl = web.ParentWeb.CustomMasterUrl;
hash["__InheritsCustomMasterUrl"] = "True";
web.Update();
}
catch { }
try {
web.AlternateCssUrl = web.ParentWeb.AlternateCssUrl;
hash["__InheritsAlternateCssUrl"] = "True";
web.Update();
}
catch { }
I hope this helps you, as I know I was pulling my hair out for a long time over this.
Enjoy!
--andrew
Correction [06.11.2008]: I just realized that in my final code, I had the following line:
web.MasterUrl = web.ParentWeb.CustomMasterUrl;
This works just fine, except I am pulling the wrong master page setting from the parent site for the current setting. This should read:
web.MasterUrl = web.ParentWeb.MasterUrl;
I have corrected this above in the code.
Tuesday, February 26, 2008
Remotely Enable Remote Desktop
- Not a big fan of editing the registry of servers
- Remote Registry service was not enabled on this particular machine
Luckily, I found the following at msgoodies.blogspot.com:
From Win2k3:
wmic /node:"Computer Name (FQDN)" /USER:"username" RDTOGGLE WHERE ServerName="Computer Name (FQDN)" CALL SetAllowTSConnections 1
From WinXP:
wmic /node:"Computer Name (FQDN)" /USER:"username" PATH win32_terminalservicesetting WHERE (__Class!="") CALL SetAllowTSConnections 1
Enjoy!
--andrew
Friday, September 21, 2007
Requiring the Contact Selector in InfoPath 2007
The one aspect of InfoPath (2003) that prevented company wide deployment at my employer was the need to have the InfoPath client in order to fill out a form. Now that Microsoft has implemented Forms Server and allowed the filling of forms via a web browser, many of my colleagues have been banging at my door for custom InfoPath solutions.
The requirement that I have been presented with was to use the Contact Selector control, to make it required, and to only allow one value. After reading the above post by Ben, which references some validation code posted in a comment on the InfoPath Team blog, it became apparent there was no easy solution for browser-based forms.
Below I offer my solution:
- Domain trust form
- No digital certificate
public void InternalStartup()
{
EventManager.FormEvents.Loading +=
new LoadingEventHandler(FormEvents_Loading);
EventManager.XmlEvents["/my:myFields/my:contactSelector"].Changed +=
new XmlChangedEventHandler(contactSelector_Changed);
}
public void FormEvents_Loading(object sender, LoadingEventArgs e)
{
XPathNavigator mainDS = this.MainDataSource.CreateNavigator();
if (this.New)
{
XPathNavigator contSel =
mainDS.SelectSingleNode("/my:myFields/my:contactSelector",
NamespaceManager);
this.Errors.Add(contSel, "ContactSelectorError",
"You must select a contact.");
return;
}
}
public void contactSelector_Changed(object sender, XmlEventArgs e)
{
if (e.Site.SelectChildren(XPathNodeType.Element).Count == 1)
{
try
{
this.Errors.Delete("ContactSelectorError");
}
catch { }
}
if (e.Site.SelectChildren(XPathNodeType.Element).Count > 1)
this.Errors.Add(e.Site, "ContactSelectorError",
"Only one contact can be selected.");
if (e.Site.SelectChildren(XPathNodeType.Element).Count < 1)
this.Errors.Add(e.Site, "ContactSelectorError",
"You must select a contact.");
}
Some notes:
- "/my:myFields/my:contactSelector" is the XPath to the Contact Selector control. This is the main group, i.e. in my example, it would be:
<contactSelector>
<Person>
<DisplayName />
<AccountId />
<AccountType />
</Person>
</contactSelector> - "ContactSelectorError" is the name of the error being added/deleted. It is not displayed to the user, but rather the internal error name for code references.
- I only add the error in the loading event for new forms, since an existing form would already have these fields required. An alternative to this.New would be to test the Contact Selector control for a value, and add the error if it's value was equal to the empty string ("").
- In the function "contactSelector_Changed", you must have a try/catch around the delete statement, because if you attempt to delete an error that does not exist, an error will be thrown.
- If you have multiple contact selector controls on your form, you will need a seperate "onChanged" event for each control, and I would suggest simply changing the name of the error from "ContactSelectorError" to something like "ContactSelectorErrorEmployee", and ensure each contact selector control has a unique name for its error. You will also need as many "this.Errors.Add" lines in the loading event as you have contact selector controls you want validated.
--andrew
Welcome!
I am not claiming that these are best practices or the only way to do things. If you have a better way to solve any of my problems, I would be more than happy to hear them.
Some things I anticipate to cover:
- SharePoint (administration and development)
- InfoPath 2007
- Web Services
- For all posts, whenever I refer to SharePoint, I am talking about MOSS2007. If I ever need to talk about SPS2003, which I doubt, I will explicitly call it by that name.
- Please do not attempt to correct my posts based solely on grammar/spelling.
- When appropriate, I will attempt to provide useful screen shots of the errors I receive and the steps I took to fix them.
- [Reserved for future disclaimers]
--andrew