Thursday, May 24, 2012

List all site owners in a site collection programmatically



The following code is a simple code to get all site owners from the site collection. Execute the following code as a console application

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.IO;

namespace MyPortal
{
    class ListAllSiteOwners
    {
     
        static void Main(string[] args)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                FileStream ostrm;
                StreamWriter writer;
                TextWriter oldOut = Console.Out;
                try
                {
                    ostrm = new FileStream("./SiteOwners.txt", FileMode.OpenOrCreate, FileAccess.Write);
                    writer = new StreamWriter(ostrm);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Cannot open  SiteOwners.txt for writing");
                    Console.WriteLine(e.Message);
                    return;
                }
                Console.SetOut(writer);

             
                using (SPSite site = new SPSite(args[0]))
             
                    foreach(SPWeb web in site.AllWebs)
                    {
                        //SPUserCollection allAdmins = web.AssociatedOwnerGroup;
                        SPGroup ownerGroup = web.AssociatedOwnerGroup;
                        if (ownerGroup != null)
                        {

                            foreach (SPUser user in ownerGroup.Users)
                            {
                                Console.WriteLine(web.Url +"\t"+ ownerGroup.Name + "\t" + user.Name);
                            }
                        }
                        web.Dispose();
                    }
             
                Console.SetOut(oldOut);
                writer.Close();
                ostrm.Close();
            });
        }
    }
}

After the code is built, you need to execute the  ListAllSiteOwners.exe from the command prompt with site collection URL as argument. 

D:\> ListAllSiteOwners http://yoursitecollectionURL

You will find the  SiteOwners.txt  file in the same location where the exe is placed. Copy the content from the text to excel for better view.

Thursday, March 29, 2012

Programmatically add a blank row at the end of a InfoPath repeating table

Code snippet to add a blank row as last row in a InfoPath repeating table. 

//Get the repeating table node
XPathNavigator Group = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:AnalysisGroup/my:AnalysisTable", NamespaceManager);
//Get the Iterator object to iterate the node to last row
XPathNodeIterator rows = Group.Select("/my:myFields/my:AnalysisGroup/my:AnalysisTable", NamespaceManager);
                      
//Loop to move the cursor to last row
for (int counter = 0; counter < rows.Count; counter++, rows.MoveNext()) ;
//clone the last row and insert it after that
rows.Current.Clone();
rows.Current.InsertAfter(rows.Current);
//move the cursor to the last row
rows.MoveNext();
                      
//Set all the fields in the row to blank
rows.Current.SelectSingleNode("my:ItemDesc", NamespaceManager).SetValue("");
rows.Current.SelectSingleNode("my:Tax", NamespaceManager).SetValue("");

Friday, March 16, 2012

Print a Web Part Zone

Requirement: To print multiple Web Parts in a Web Part zone from the home page of a Web site.

Following are the steps to achieve this

1. Add the Web Parts in a Web Part Zone

2. Open the site in the SharePoint Designer, open the home page aspx file, select the Web Part Zone that you want to take the print out in the design view,  and wrap the Web Part zone by adding a <div> tag,


<div id="WebPartZone1">
<table width="100%"  cellpadding=0 cellspacing=0 style="padding: 5px 10px 10px 10px;">
 <tr>
  <td valign="top" width="70%" colspan="4">
  <WebPartPages:WebPartZone .................
                                    ..................................
                                      ..............................
                              </WebPartPages:WebPartZone>
                    </td>
                    </tr>
                     </table>
</div>


3. Add a Content Editor Web Part in the Zone and add the following script code in the source




<style type="text/css">
.styled-button-2 {
-webkit-box-shadow: rgba(0, 0, 0, 0.0976562) 0px 1px 0px 0px;
background-color: #EEE;
border: 1px solid #999;
color: #666;
font-family: 'Lucida Grande', Tahoma, Verdana, Arial, Sans-serif;
font-size: 11px;
font-weight: bold;
padding: 2px 6px;
height: 28px;
}
</style>
<div id='printButton' align="right"><input type="button" class="styled-button-2" OnClick="javascript:void(PrintWebPart())" value="Print Dashboard"></div>

<script language="JavaScript">
//Controls which Web Part or zone to print
var WebPartElementID = "WebPartZone1";

//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 prButton = document.getElementById('printButton');
        prButton.style.display = 'none';
   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();
}
prButton.style.display = '';
}
</script>

Thursday, February 16, 2012

Trigger event when field value changed in Infopath Repeating table programmatically

Requirement: To update a field value in a repeating table when another field value is changed.

Solution: In the Infopath form, select the field that you want to apply event, go to Tools menu, select Programming > select Changed Event


This will redirect you to the VSTO event, write the code to change the main data source.

Thursday, January 26, 2012

'NaN' in InfoPath Decimal/ percentage field

In InfoPath 2007, we used to get NaN in our calculated decimal fields. So, I tried to add a Rule to check if the value is NaN and replace it is with '0' if it is true. However, there is no option to check if the value of a decimal field with a text NaN
NaN error in calculated decimal fields

So the workaround for this is, change the field type to text and add the rule as below. After creating the rule, again change the field type to Decimal.

NaN error in calculated decimal fields

Wednesday, January 25, 2012

Sumproduct in InfoPath 2007

An workaround to do similar to excel Sumproduct function in InfoPath 2007

We had a requirement to calculate the sum of product of 2 column in a repeating table. See the screen shot below

Sumproduct in InfoPath 2007

Sales Tax is a Decimal field with Percentage format enabled
Quantity is an integer
Purchase Price is Decimal field
Monthly Total is Decimal field

We want the Monthly Total value to be
Monthly Total = Sum(Quality * Purchase Price) * percentage of Sales Tax

Since there is no option to do the sum(Quality * Purchase) in InfoPath as  SUM XPath function takes only a node set as parameter, I've created a field named QuantityPurchasePrice to have the product of Quality and Purchase Price and made the field hidden by setting the conditional formatting as below

Sumproduct in InfoPath 2007


Now apply the following formula in the Total field

sum(QuantityPurchasePrice) * (1 + SalesTax)


..and with some sample value, the output is

Calculate Sumproduct in InfoPath 2007



Monday, January 23, 2012

unbound (control cannot store data)

Scenario: In Design view of a InfoPath 2007 form, had several controls within a table and the table is placed within a section control. Deleted the section control and got the following error in all the controls within the section

Issue: Error in controls as "unbound (control cannot store data)"

Reason: The controls has unbind

Resolution: Right click each control, click Change Binding and from the data source, select the appropriate field in which to store the control data .

InfoPath Change Binding