Monday, October 15, 2012

Get data from InfoPath form using Object Model(C#)

The InfoPath forms (.xml) files stored in the following Path
Open the site inthe SharePoint desinger, click on All Files folder and list -> Open any xml file

  <my:group7>
    <my:group8>
     <my:ListOfAttendee>Ravi</my:ListOfAttendee>
     <my:Organization>Financial Services</my:Organization>
    </my:group8>
    <my:group8>
     <my:ListOfAttendee>Kumar</my:ListOfAttendee>
     <my:Organization>IT Department</my:Organization>
    </my:group8><my:group8>
     <my:ListOfAttendee>Mohan</my:ListOfAttendee>
     <my:Organization>HR</my:Organization>
    </my:group8>
   </my:group7>


use the below code:

SPFile file = properties.ListItem.File;
           if (file == null)
               return;
           // Get the binary data of the file
           byte[] xmlFormData = null;
           xmlFormData = file.OpenBinary();

           // Load the data into an XPathDocument object
           XPathDocument ipForm = null;
           if (xmlFormData != null)
           {
               using (MemoryStream ms = new MemoryStream(xmlFormData))
               {
                   ipForm = new XPathDocument(ms);
                   ms.Close();
               }
           }
           if (ipForm == null)
               return;
           // Create an XPathNavigator object to navigate the XML
           XPathNavigator ipFormNav = ipForm.CreateNavigator();
           ipFormNav.MoveToFollowing(XPathNodeType.Element);
           XmlNamespaceManager nsManager =
           new XmlNamespaceManager(new NameTable());
           foreach (KeyValuePair<string, string> ns in ipFormNav.GetNamespacesInScope(XmlNamespaceScope.All))
           {
               if (ns.Key == String.Empty)
               {
                   nsManager.AddNamespace("def", ns.Value);
               }
               else
               {
                   nsManager.AddNamespace(ns.Key, ns.Value);
               }
           }
           // Retrieve the value of the field in the InfoPath form
           //XPathNavigator nodeNav = ipFormNav.SelectSingleNode("//my:DisplayName", nsManager);
           XPathNodeIterator rows = ipFormNav.Select("//my:group7/my:group8", nsManager);
           string _Attendees = "";
           string _Organization = "";
           DataTable table = new DataTable();
           table.Columns.Add("List of Attendees", typeof(string));
           table.Columns.Add("Organization", typeof(string));
           while (rows.MoveNext())
           {
               _Attendees=rows.Current.SelectSingleNode("my:ListOfAttendee", nsManager).Value;
               _Organization = rows.Current.SelectSingleNode("my:Organization", nsManager).Value;
               table.Rows.Add(_Attendees, _Organization);
            }
          
        SPListItem list = AttendeesDetailsList.Items.Add();
                   list["Title"] = properties.ListItemId;
                   list["ListOfAttendee"] = _Attendees;
                   list.Update();

Wednesday, September 19, 2012

Hide First Tab (Home) in SharePoint 2010 Navigation

image
You will notice that the Home tab actually is the first node and then has a child UL which represents the rest of the navigation Items. So the approach is to hide the first <li> <a> (display: none) and then simply just use (display:block ) to show the hidden <ul> <li> <a> tags.
Here is the CSS you could use to hide just the first node (home) tab in a SharePoint 2010 application:

Place Content Editor WebPart  and add the below code

<style type="text/css">
.s4-tn li.static > a{
display: none !important;
}
.s4-tn li.static > ul a{
display: block !important;
}


</style>
image

Tuesday, September 11, 2012

Customization SharePoint 2010 - Ribbon

http://www-kga.csharpcorner.com/tags/Create-Custom-Tab-in-Office-Ribbon

Printing SharePoint WebPart content

Try the following steps. It works for most web parts (i
have used this for lists)

1. Start with a web part
You start by having a web part with a display of information, such as a list.
If you don’t have one already you can start by creating a SharePoint Event List,
and then, adding a Calendar web part (remember to choose the Calendar View).
2. Add the Print Button
You will be adding a Print Button to the page, by putting the JavaScript below
into a Content Editor Web Part.
Add a Content Editor Web Part to the page with the web part you want to print.
Open its properties and click the Source Code button to add the JavaScript code.
Copy the following code directly into the Text Builder box. This code will
create a “Print Web Part” button that when clicked, will execute the print
action.
<center><input type="button" OnClick="javascript:void(PrintWebPart())"
value="Print Web Part"></center>
<script language="JavaScript">
//Controls which Web Part or zone to print
var WebPartElementID = "WebPartWPQ6";
//Function to print Web Part
function PrintWebPart()
{
var bolWebPartFound = false;
if (document.getElementById != null)
{
//Create html to print in new window
var PrintingHTML = '<HTML>\n<HEAD>\n';
//Take data from Head Tag
if (document.getElementsByTagName != null)
{
var HeadData= document.getElementsByTagName("HEAD");
if (HeadData.length > 0)
PrintingHTML += HeadData[0].innerHTML;
}
PrintingHTML += '\n</HEAD>\n<BODY>\n';
var WebPartData = document.getElementById(WebPartElementID);
if (WebPartData != null)
{
PrintingHTML += WebPartData.innerHTML;
bolWebPartFound = true;
}
else
{
bolWebPartFound = false;
alert ('Cannot Find Web Part');
}
}
PrintingHTML += '\n</BODY>\n</HTML>';
//Open new window to print
if (bolWebPartFound)
{
var PrintingWindow = window.open("","PrintWebPart",
"toolbar,width=800,height=600,scrollbars,resizable,menubar");
PrintingWindow.document.open();
PrintingWindow.document.write(PrintingHTML);
// Open Print Window
PrintingWindow.print();
}
}
</script>
3. Connect the Print Button to the Web Part
To do this we need the <DIV> tag ID for the Web Part we want to print, then,
we modify the ID in the JavaScript of the Print Button.
To find out the ID of the Web Part we want to print:
Using your browser, right mouse click on the page where the Web Part is
installed and choose “View Source”. This will open a view of your page in HTML
within Notepad.
Press CTRL-F, to initiate a Find. Enter the Title of your Web Part. You may need
to execute a find a couple of times as your navigation may show “Events” as
well.
Once you have located the HTML for your Web Part for example; “<td accesskey="W"
tabindex="0" title="Events" id="WebPartTitleWPQ6" style="width:100%;">”, look
later in the HTML for a <DIV> tag which matches the Web Part Queue Number, in
this case WPQ6. In our case it looks like “<div
WebPartID="d44df3e3-0bbc-4151-9d04-22982bd294bc" HasPers="false"
id="WebPartWPQ6"…”.
The “WebPartWPQ6” would be the ID we want. The key part of the ID is to know if
it is 1, 2, 3, etc. Here it is 6.
To modify the Print Button JavaScript:
Modify the Content Editor Web Part which contains the JavaScript you pasted
earlier and go into the Source View.
Look for the line “//Controls which Web Part or zone to print”, the line
underneath controls the ID near the top.
Replace the “WebPartWPQ6” with the ID you copied from the source of the page and
click “OK”.
Save the changes and click OK.
4. Print the Web Part Content
We are now ready to test what you have labored to create. Once the page has
been refreshed inside of Internet Explorer, click on the “Print Web Part”
button. You should see a new Window with the content of your web part.
If your pop-up blocker IS NOT turned on, you will get the Print Dialogue.
If it is turned on, then you can go to File Print or Print Preview.
Now, print the content.

Wednesday, August 22, 2012

Programmatically generate/update data for an InfoPath Form and save it in a SharePoint Form Library

Steps
 1) Create an Infopath form using the Microsoft InfoPath desinger. and publish the infoPath form into respective form library. I also created an empty form in the form library based on this template (BLANK.xml). This example opens an empty form (BLANK.xml) from the form library, reads it into an xml document, parses the xml document to update the fields, and then saves the xml document as a new file back to the form library.

2)
// opens the site
SPWeb webSite = new SPSite(txtUrl.Text).OpenWeb();
// gets the blank file to copySPFile BLANK = webSite.Folders["Test1"].Files["BLANK.xml"];
// reads the blank file into an xml documentMemoryStream inStream = new MemoryStream(BLANK.OpenBinary());
XmlTextReader reader = new XmlTextReader(inStream);
XmlDocument xd = new XmlDocument();
xd.Load(reader);
reader.Close();
inStream.Close();
//gets the root element from the xml documentXmlElement root = xd.DocumentElement;
//the loop counter is started at 2 to skip past the namespace tags and start at the data fieldsfor(int index=2; index<root.ChildNodes.Count; index++)
{
//insert code to parse the xml to update the fields}

// saves the XML Document back as a fileSystem.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
SPFile newFile = webSite.Folders["Test1"].Files.Add("Test_Document.xml", (encoding.GetBytes(xd.OuterXml)), true);


XPath queries could also be used to find and update fields in the xml instead of or in addition to looping through the nodes of the xml document. Another alternative to this would be to use the myschema.xsd from the .xsn file and load a strongly typed dataset based on that schema with the xml, update the fields in the dataset, then write the dataset to xml and appending the proper header tags at the top xml to include the InfoPath namespace information. This could also be slightly modified to open an existing form in a SharePoint form library, update the data elements, and save it back to the form library.

Wednesday, August 15, 2012

Show/hide Two WebParts based on usergroups in Landing page

1) Create custom Document Library (ex: Pages) break the permissions and assign NT authenticated Users as read permissions
2) Create Web Part Page on SharePoint site
2)      Give proper name for Landing Page(ex: Default.aspx) and select the "Pages" from Document Library dropdown
3) Add 2 Content Editor WebParts on created page
4) Assign the groups to First Content Editor WebPart as Taget Audience
5) In content Editor HTML source, add the id to DIV tag (ex: <div id="authenticatedContent"> we need to use this id in second content editor webpart script file for verifying length)
6) Open the Second Content Editor WebPart HTML Source and add the below script
<div id="noaccessmsg"></div>
<script language="javascript" src="/root/root/SiteAssets/js/jquery-1.7.2.min.js"></script><script type="text/javascript">

if ($("#authenticatedContent").length == 0){                               
    $('#noaccessmsg').html("No Access")
}</script>

thats it.........................All the best...........

Monday, August 6, 2012

How to Configure Form Based Authentication (FBA) in SharePoint 2010

I found good article(step by step) on Internet and posting here ........enjoy :)

Introduction

This article explains step by step information on configuring Form Based Authentication (FBA) in SharePoint 2010. This article would be useful for developers/designers/architects and those who want to implement form based authentication (FBA) for their SharePoint 2010 sites as a business requirement.
We cannot use the classic / basic claimed based authentication for all business scenarios. I was recently working on a consumer portal or product selling site where form based authentication is most appropriate. This article resolves authentication issues by configuring a SharePoint 2010 site with form based authentication.

Difference between MOSS 2007 and SharePoint 2010

There is no huge difference in configuring FBA for a MOSS 2007 site and a SharePoint 2010 site. You cannot implement FBA for a SharePoint 2010 class authentication site. FBA can be implemented only for a claims authentication site in SharePoint 2010.
In MOSS 2007, it is required to configure the web.config file of the FBA site and Central Administration site. In SharePoint 2010, it is required to configure the web.config file of the FBA site, Central Administration site, and the Security Token Service (STS) web.config file. STS is one of the next generation Single Sign On services used to store credentials of an application in SharePoint 2010.
I have also written article on enabling FBA in a MOSS 2007 site in CodeProject and Blogger and is available here. CodeProject: http://www.codeproject.com/Articles/19055/Form-Authentication-for-MOSS-2007-Site, Blogger: http://nagendra-gunaga.blogspot.in/2012/03/form-based-authentication-fba-for-moss.html.  

Steps to Configure FBA in SharePoint 2010 

Below are the steps required to configure FBA in SharePoint 2010. I will be using MS SQL database as membership store for users.
A) Setting up ASP.NET Forms Authentication User and Role Data Source
1. Create Database
2. Configure Membership and Role Provider
3. Create User
B) Create Web Application and Site Collections
C) Configure Web.Config file 
1. Configuring FBA web application web.config file
2. Configuring Central Administration web application web.config file
3. Configuring Security Token Service web.config file
D) Adding User Policy to the FBA Web Application
E) Verification Steps

A) Setting up ASP.NET Forms Authentication User and Role Data Source 

This section explains creation of database which is used to store user's information such as credentials and roles which is used for Form Authentication. This section also explains the configuration of Membership and Role providers in the web.config file and creation of users using ASP.Net configuration wizard. This article shows creating a user and which will be used for testing Form Authentication later.

1. Create Database 

To create database, Microsoft has provided a tool/ utility called
aspnet_regsql.exe that creates a database for us. This utility can be found in %windir%\Microsoft.Net\Framework64\v2.0.50727 folder. Please see the image below: 

Executing aspnet_regsql.exe file will open ASP.Net SQL Setup wizard that will walk through creating the ASP.Net database. I have added the database name as FBANetDB and configured it for windows authentication. Please see the image below:

Click on Next button. Please see the image below:

Select Configure SQL Server for application services option and click Next button. Please see the image below:

Click Next button. Now the database FBANetDB is created successfully. Please see the image below:



2. Configure Membership and Role Provider 

In the previous section, database is created successfully. Now we need to add a user in to database. Using ASP.NET Configuration Wizard, users can be added the database. This can be achieved by creating web site that will allow us to add the users and roles and also ensure the database connection strings, membership and role providers are correctly configured before we bring SharePoint in to equation.
Below steps explains creating web site and configuring membership and role providers and executing ASP.Net Configuration Wizard.
a) Open Visual Studio 2010 and select File ? New ? Web Site. In the New Web Site dialog, select the ASP.Net Web Site template and enter the location to store the web site files. Please see the image below:

You can choose any location whichever is comfortable for you. web.config file will be added to project automatically.

b) By default, you will see a <connectionStrings/> node within <configuration> node. Specify the connection string to the database which has been created in the previous section. Please see the image below:

 

I have mentioned server as GUNAGA1. This is the server in which SQL Server 2008 is installed. Please mention the respective server name.
Also add the membership provider and role provider within <system.web> tag. See the below image for more information.

 

c) Save web.config file and launch the ASP.Net Configuration Wizard by clicking on Website ? ASP.Net Configuration. Please see the image below:

  

d) Set the authentication type in the above wizard. To do this, click Security link. In the Security tab, under Users section, click Select authentication type link. Select From the internet option and press Done button which is available in the bottom right corner. By selecting this option, which means that site will use form authentication to identify users. Please see the image below:

  


e) To test the membership and role providers, click on Provider tab. In the Provider tab, click on Select a different provider for each feature (advanced) link. Select right / correct membership and role provider and click Test link to ensure that providers are communicating to right database.

At this point, we configured web.config file with connection string and providers information. Also we tested the providers with the database. Next section will explain adding users to database.

3. Create User 

a) To add users, click on Security tab. In Security tab, under Users section, click Create user link. Here I am adding user as testFBA and password as password which will be used for testing form authentication later. Please see the image below:

  


Now we have created a user successfully. Do not worry about creating roles at this time and will be explained later.

B) Create Web Application and Site Collection 

Follow the below steps to create web application and site collection.
a. Go to Central Administration ? Application Management ? Select ‘Manage Web Application’ link present under ‘Web Applications’ section.
b. Click on ‘New’ option in the ribbon.
     1. See the below image for ‘Authentication’ and ‘IIS Web Site’ section.

         

     2. See the below image for ‘Security Configuration’ and ‘Claims Authentication Type’ section.

          

     3. See the below image for configuring ‘Sign In Page URL’ and ‘Public URL’ section.

        

     4. See the below image for configuring ‘Application Pool’ and ‘Database Name and Authentication’ section.

         

     5. Create Site Collection after creating web application. Select the template whichever you want to create site collection.

C) Configure We.Config file

1. Configuring FBA web application web.config file 

Open FBA web application web.config file and add the below entries.
     a. Add Connection String. Connection String has to be added after </SharePoint> and before <system.web> tag. See the below image for more information.

           

     b. Add Membership Provider and Role Provider

         

2. Configuring Central Administration web application web.config file 

Open Central Administration web application web.config file and add the below entries.
     a. Add Connection String. Connection String has to be added after </SharePoint> and before <system.web> tag. See the below image for more information.

           

     b. Add Membership Provider and Role Provider

         

3. Configuring Security Token Service web.config file 

Open Security Token Service web.config file from %Program Files%\Common Files\Microsoft Shared\web server extensions\14\Web Services\SecurityToken location and add the below entries.
a. Add Connection String. Connection String has to be added above <system.web> tag. See the below image for more information.

b. Add Membership Provider and Role Provider

D) Adding User Policy to the FBA Web Application 

Follow the below steps to add user policy to the web application.
a. Go to Central Administration ? Manage Web Applications ? Select the FBA web application and click on ‘User Policy’ option in the ribbon.

b. Click on ‘Add Users’ link and select ‘Default’ as the zone and click on ‘Next’ button.


c. Type the user name created in ‘Create User’ section in the ‘Users’ textbox and click on people picker icon. You should see the user name get underlined in the ‘Users’ textbox.

d. Follow the verification steps to test form based authentication.

E) Verification Steps 

1. Go to FBA SharePoint site and select ‘Forms Authentication’ option.

2. Enter User Name and Password and select ‘Sign In’ button.

3. You should be redirected to home page.


Friday, August 3, 2012

BeforeProperties/AfterProperties in Event Receivers

As many of you know, event receivers are a great way to hook into various SharePoint events.  These can apply to Feature events such as FeatureActivated, List events such as FieldAdded, and many others.  The most common set of receivers used, however, are part of SPItemEventReceiver which let you wire your code up to a number of events that can occur to items on a list or library.
When working with events, you’ll quickly find that before (synchronous) and after (asynchronous) events exist, and the method suffix such as “ing” (e.g. ItemAdding) and “ed” (e.g. ItemAdded) will tell you whether it gets invoked before or after the actual change is made.  Basic stuff.
And, as you get deeper, you’ll even find that you can extract the before and after state of the change.  For example, you can hook into the ItemUpdating event for a document library and prevent a user from changing a certain column.  The code might look like this:
public override void  ItemUpdating(SPItemEventProperties properties)
{
     if (properties.BeforeProperties["column"] != properties.AfterProperties["column"])
    {
        properties.Cancel = true;
        properties.ErrorMessage = "This column cannot be changed";
    }
}
For a document library, this works just fine.  However, you should know that the BeforeProperties hash table is not populated for items on a list.  As is worded in the SDK: “For documents, Before and After properties are guaranteed for post events, such as ItemUpdated, but Before properties are not available for post events on list items”
When they say “not available for post events on list items”, do they mean after events (like ItemUpdated, ItemDeleted, etc)?  The wording is curious here, so I thought I’d take some time to test each combination of common events such as Add, Update and Delete.  These were done across a custom list and then a document library.  Each test involved adding a new item, editing the item and then deleting the item.  Here are the results for a list:
ListBeforePropertiesAfterPropertiesproperties.ListItem
ItemAddingNo valueNew valueNull
ItemAddedNo valueNew valueNew value
ItemUpdatingNo valueChanged valueOriginal value
ItemUpdatedNo valueChanged valueChanged value
ItemDeletingNo valueNo valueOriginal value
ItemDeletedNo valueNo valueNull

No value means that column value in the hash table was not available. 
New value means that the correct value for the column was available. 
Changed value means that the correct updated value was available.
Original value means that the correct original value was available.

Here is the same test against a document library:
LibraryBeforePropertiesAfterPropertiesproperties.ListItem
ItemAddingNo valueNo value Null
ItemAddedNo valueNo valueNew value
ItemUpdatingOriginal valueChanged valueOriginal value
ItemUpdatedOriginal valueChanged valueChanged value
ItemDeletingNo valueNo valueOriginal value
ItemDeletedNo valueNo valueNull


Properties.ListItem refers the the current value for the list item at that point in the event.  Null means that the item is not available.  My analysis yields the following results:
  • Not surprisingly, we get null values for for ItemAdding (before item is added) and ItemDeleted (after item is deleted).  This was proven by Ishai Sagi some time ago.
  • As correctly documented in the SDK, item events for lists do not expose BeforeProperties.
  • ItemAdding and ItemAdded correctly report the value in the AfterProperties for an list item, but not a library item.  This is curious.
  • We have no visibility on the previous states during the ItemDeleted event.  Once it’s deleted, it’s clearly gone.

So, if we go back to our original problem listed above.  How can we prevent a user from changing a certain column for an item in a list event?  From the list table, you can see if we hook into the ItemUpdating event, we can compare the current item’s value (properties.ListItem) to the AfterProperties value.  The code would look like this:
if (properties.ListItem["column"] != properties.AfterProperties["column"])
{
    properties.Cancel = true;
    properties.ErrorMessage = "This column cannot be changed";
}

Thursday, July 19, 2012

Create a Search Scope for a Sharepoint 2010 List or Library

Update: I’ve just recorded a screencast tutorial on creating a search scope: click here
Go to Site Actions > Site Settings (make sure you’re in the root site), and click “Search scopes”.

Click “New Scope” to create a new scope to load in a sub-page of the site.

Nothing really needs to be set on this screen except the title. If you want this to be a default scope that shows in the normal scope dropdown, make sure and select the “Search Dropdown” box. Otherwise, everything can be set in your custom page.

In the next screen you’ll see your newly created scope under “Unused Scopes”. There are no rules attached to this scope yet, so let’s go create some. Click “Add rules”.

If you want this search scope to query a specific list (for instance, I wanted it to troll through the “newlist” list), enter the address of the list in the “folder” textbox. Also, if you check “require” it will designate that only this list will be searched.

I’m not exactly sure how often the scopes update, but it seems to be about every 15 minutes. I assume it depends on how your server is setup.

Next, create a new page. In this page, add some webparts. Add the following 3 webparts:
  • Search Box
  • Search Core Results
  • Search Paging

Search Box
When you add the search box webpart, the only thing I would change is the page which displays the result. I want to display the results on this page, not on the typical search page. So I just put the address of the page I’m on. That way it will send the search results to this page’s results webpart.

Search Core Results
Here is where you need to input the scope. Edit the webpart and look for the “location properties” section. Under “Scope” type the name of your scope (human readable is fine).

Click OK, reload the page, do a search, and now the search results should only show items in your list!

SharePoint 2007 Page Life Cycle

  1. User request the SharePoint Page using http
  2. ASP.NET calls the WSS File provider
  3. WSS file provider returns the page from File or Database
  4. Page is parsed by SafeMode parsor if required
  5. Returned page is complied by ASP.NET Compiler
  6. WSS File provider collects the page layout class and complies it
  7. ASP.NET engine adds SharePoint Context Data to the site meta data and retreives the associated master page.
  8. Master page got compiled and responded back to the user.

ASP.NET Page Life Cycle

ASP.NET Page Life Cycle 

When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering. It is important for you to understand the page life cycle.
General Page Life-cycle Stages (Courtsy MSDN, CP, UsualDosage, Several Blogs...)
In general terms, the page goes through the stages outlined in the following table. In addition to the page life-cycle stages, there are application stages that occur before and after a request but are not specific to a page.



Putting together an acronym for the page life cycle is easy enough. Since the Page Request technically isn't a part of the life cycle (it only indicates whether we actually will start the cycle or load a cached page) we won't include it in the acronym.
S � Start
I � Initialize
L � Load
V � Validate
E � Event Handling
R � Render
That gives us "SILVER", which is very easy to remember. However, it is important remember that the last part of the cycle is unload. You can remember it as "SILVER-U" or "SILVER-YOU" if that helps !!! Now that it's easy to remember the order of steps for the page lifecycle, we'll summarize exactly what happens and what events are pertinent to each stage.

1. Start
This is where page properties such as Request, Response, IsPostBack and UICulture are set. As a developer, you most likely won't really need to do anything in this stage of the cycle. If you need to access or override behavior for this step, use the PreInit method to create or re-create dynamic controls, set a master page or theme or read or set profile property values. It is important to note that if the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.

2. Initialize
This stage can be very important to developers. Here, themes are applied, and unique ids are generated and set for controls. Developers have access to the Init, InitComplete and PreLoad methods in this stage. Microsoft's recommended usage for these methods is as follows:
Init � This event is raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties.
InitComplete � This event is raised by the Page object. Use this event for processing tasks that require all initialization be complete.
PreLoad - Use this event if you need to perform processing on your page or control before the Load event. After the Page raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.

3. Load
This stage is perhaps the most utilized by developers. In this stage controls are loaded with information retrieved from view and control states. The OnLoad is the event method that fires during this stage. This is where you will want to set properties for all of the server controls on your page, request query strings, and establish database connections.

4. Validation
If you have controls that require validation, they are validated here and you can now check the IsValid property of the control. The event associated with this is Validate, which contains one overloaded method that accepts a validation group string. The overloaded method instructs the controls in the specified group to validate.

5. Event Handling
The event handling for server controls occurs during this stage. This means that events such as Click, SelectedIndexChanged, etc are applied to your server controls, and, in the case of a postback, these event handlers are fired by the control. The accessible events of note in this stage are as follows:
LoadComplete � At this step, all of the controls for the page have been loaded.
PreRender � A few things of import happen here. First, the page object will call EnsureChildControls for each control, and finally for the page. Additionally, any data bound control that has a DataSourceID set will call its DataBind method. It is important to note that the PreRender event occurs for each control on the page. At the conclusion of this event, ViewState will be saved for the page and all of the controls.
SaveStateComplete � ViewState has been saved. If you have actions that do not require changes to controls but require ViewState to have been saved, you can handle the SaveStateComplete event.

6. Render
Render is not really an event. Rather, the page object calls this method on each control, which in turn writes out the HTML markup for the control to the browser. This stage is keenly important to developers who create custom controls, because the standard approach is to override the Render method for the control in order to output the custom markup. If your control inherits from a standard ASP.NET server control, you probably won't need to override the Render method unless you want to exhibit a different behavior than the control's default. This is outside the scope of this document, but for more reading, you can reference Microsoft's Developing Custom ASP.NET Server Controls. (http://msdn2.microsoft.com/en-us/library/zt27tfhy.aspx)

7. Unload
This final event occurs first for each control, then, finally, for the page. At this point, all controls have been rendered to the output stream and cannot be changed. During this event any attempt to access the response stream will result in an exception being thrown. This event is primarily for cleanup routines such as closing open database connections and open file streams, or, event logging and other tasks.

Methods
The following methods (which can all be overridden) occur in order during the lifecycle of an ASP.NET page. Please realize that some of these methods are called recursively, and multiple times depending on the content of the page. This list is the generalized order in which methods fire when a page loads.

Thursday, June 7, 2012

Copying/Moving SharePoint 2010 Designer Workflows

Most often, we required moving or copying a workflow that is created using SharePoint designer between sites or site collections. This was straight forward in SharePoint Designer 2007. You just need to copy the content of the workflow’s config(workflow.xoml.wfconfig.xml) file and the rules file & replaced the list GUID’s. But in SharePoint Designer 2010, there is a little tweak associated with it.
There was an option in SharePoint Designer, Export to Visio which exports your workflow as a .vwi file, and can be imported in to another site using the option Import from Visio.  But when you try that option, you will get the below message.
This workflow cannot be imported because it was created in SharePoint Designer for a different site, or the original workflow has been moved or deleted. To move a workflow between sites, use Save as Template (.wsp file) instead of a Visio workflow drawing.
So, to achieve the same follow the steps below.
  1.  In the first(source) site, create the required workflow and publish it.
  2. Now select Export to Visio option which allows you to save the workflow with a .vwi extension. (Refer this workflow hereafter as source workflow).
  3. Now go to the destination site where you want the workflow to be copied, and create a new workflow with the same name as the previous one & publish it.
  4. Now select Export to Visio option which allows you to save the workflow with a .vwi extension. (Refer this workflow hereafter as Destination workflow).
  5. Now you will be having two .vwi files (one of source workflow’s – SourceWorkflowName.vwi  and other of the destination workflow’s – DestinationWorkflowName.vwi). Now add .zip extension to both the files. Now your files names should be SourceWorkflowName.vwi.zip & DestinationWorkflowName.vwi.zip.
  6. Now open both the zip files, copy workflow.xoml.wfconfig.xml from destination workflow to source workflow. (Its destination to source and not source to destination).
  7. From now on, we will not use the file DestinationWorkflowName.vwi.zip.  So ignore that file.
  8. Remove the .zip extension from SourceWorkflowName.vwi.zip which gives you the   SourceWorkflowName.vwi file.
  9. Now, go to the destination site, open workflows and click Import from Visio and browse to the SourceWorkflowName.vwi file.
  10. That’s it and your workflow is copied. You can publish the workflow and run it.
PS : In case if your list’s GUID’s (for those lists that you have used in workflow – tasks list, history list or any other lists used in workflow steps) have been changed from source & destination site, you may need to update those steps in the workflow.

Wednesday, May 23, 2012

Emulate User Roles in InfoPath Forms Services to Automatically Switch Views


Many of my SharePoint consulting clients and students express the need to have different users see different views of an InfoPath form. In the InfoPath client, this is easy to handle using the User Rolesfunctionality which has been well-documented elsewhere. Unfortunately, User Roles are not supported by InfoPath Forms Services for your browser-enabled forms. Here is a work-around that I have been using for quite some time that has worked well for me and my clients and students.
In this post we'll create a simple InfoPath form with two views: one view for most users and another view for administrators only. When the form loads, it will check to see if the current logged in user is an Administrator for that form and if he is it will display the Admin View to the user. If the user is not an administrator for the form, it will display the User View.
Create a Custom List to Store Users and Permission Levels
Although SharePoint exposes a number of web services that reveal security information and information about SharePoint Groups, I've never been able to get them to work reliably with InfoPath, especially without writing code. Since I can't use SharePoint Groups, I create a custom list to store the names of my users who will be administrators.
  1. Create a custom list called My Form Admins.
  2. Change the name of the Title column to Permission Level.
  3. Create a new column named User, of type Person or Group. Set the Showfield to User Name.
  4. Add a couple users.
  5. Your list should look similar to this:
Create a New InfoPath Form with Two Views
Obviously, you'll need an InfoPath form to use this, so launch InfoPath and create a new blank form.
Within this form, create two views. Rename the default view to User View, name the other one Admin View. You don't have to add any fields on these views, but you can if you want. You will want to make them distinct so you know which view you are looking at, but it could be as simple as just putting the text "User View" and "Admin View" on the top of each view; that's what I did for this post.
Add Some Nodes to Store the Decisioning Information
In my form, I created a new group named AdminCheckingNodes, with two nodes both of type Text named Current UserUserName, and CurrentUserPermissionLevel. These will be used to store the User name of the current logged in user and his permission level, if one is set, in the My Form Admins list in SharePoint.

Add a Data Connection to the SharePoint List Containing the Admin Names
The form needs to be able to look at the My Form Admins list in SharePoint to determine the Permission Level of the current user. Create a data connection to this list.
  1. Click on Tools, Data Connections.
  2. Click Add.
  3. Create a new connection to Receive Data
    from a SharePoint Library or List.
  4. Paste in the path to the My Form Admins list.
  5. Select the My Form Admins list.
  6. Select both the Permission Level and User fields.
  7. Accept all the other defaults in the wizard and close the Data Connection window.
Write Rules to Get the Current User's Permission Level
You need to write four rules to fire when the form first loads.
The first rule will store the name of the current user in the CurrentUserUserNamenode.
  1. Click on Tools, Form Options.
  2. Select the Open and Save category.
  3. In the Open Behavior section , click on the Rules button.
  4. Click the Add button.
  5. For the Rule Name, enter "Store Name of Current User".
  6. Click the Add Action button.
  7. Select the
    Set a field's value
    action.
  8. For the Field, select the CurrentUserUserName node.
  9. For the Value, click the Data Binding button. Click the Insert Function button, select userName. Click OK, and OK. Your form should look like this:
  10. Click OK. The completed rule will look like this:
  11. Click OK to close the Rules dialog.
Whew! That may have seemed like a lot, but it's only part of what we need to do. You still need to write three more rules. Your Rules for OpeningForms dialog should look like this.
  1. Click the Add button.
  2. For the Rule Name enter, "Clear out the current permission level". You need to do this just to make sure this field is empty in case the current user isn't listed in you're My Form Admins list.
  3. Click the Add Action button.
  4. Select the
    Set a field's value
    action.
  5. For the Field, select the CurrentUserPermisisonLevel node.
  6. For the Value, just leave the field blank. Click OK, and OK. Your form should look like this:

  7. Click OK. The completed rule will look like this:
  8. Click OK to close the Rules dialog.
  9. You should have two rules now. You're half done!
The next rule will look at the SharePoint list and store the permission level of the user, if the user's name is in the list.
  1. Click the Add button.
  2. For the Rule Name enter, "Look up and store the current user's permission level".
  3. Click the Add Action button.
  4. Select the
    Set a field's value
    action.
  5. For the Field, select the CurrentUserPermisisonLevel node.
  6. For the Value, click on the data binding button.
  7. In the Insert Formula dialog, click on the Insert Field or Group button.
  8. Change the Data Source to My Form Admins (Secondary).
  9. Expand out all the nodes and select Permission Level.
  10. Click on the Filter Data… button.
  11. Click the Add button.
  12. In the first drop-down, select Select a field or group….Then select User, then click OK.
  13. Leave the second drop-down with is equal to.
  14. In the third drop-down, select Select a field or group….Then change the Data Source to Main, select the CurrentUserUserName node. Your condition should look lieke this:
  15. Click OK on the next four dialogs. Your form should look like this:
  16. Click OK three more times. Your rules should look like this:
You're almost done!. Just one more rule to write, then you can publish and test your form. The last rule will look at the value stored by the previous rule and will switch views if it contains the word "Admin."
  1. Click the Add button.
  2. For the Rule Name enter, "Switch to admin view if user is an admin".
  3. This rule will have a condition to check the permission level you stored with the previous rule. Click the Set Condition button.
  4. In the first drop-down, select Select a field or group….Then select CurrentUserPermissionLevel, then click OK.
  5. Leave the second drop-down with is equal to.
  6. In the third drop-down, select Type Text….Type the word "Admin" without the quotes; InfoPath will automatically add quotes for you. Your condition should look like this:
  7. Click OK.
  8. Click the Add Action button.
  9. Select the
    Switch Views
    action.
  10. For the view, select the Admin View, and click OK.
  11. Your completed rule will look like this:
  12. Click OK. All four rules should look like this:
  13. Click OK twice to return to your form.
Publish and Test the Form
Now you're ready to test the form! Woohoo! The easiest way to do this is to switch to the User View, then click the Preview button. If you are not listed as an Admin in the My Form Admins table, you shouls see the User View.


Close the form, add yourself as an Admin in the SharePoint list and then preview the form again. You should see the Admin view.


Conclusion
You can do a lot more with this besides just switch views. For example, depending on the permission level you set for the current user, the form may call different web services to populate certain fields of information. You could choose to show or hide different sections using Conditional Formatting. When users with certain permission levels submit the form, you may have a SharePoint Designer workflow check to see if it was submitted by an Administrator, and if it was, do something different than if it was submitted by a regular user. The uses of this are limitless. Let me know in the comments how you plan to make use of this.