A Practical Guide to SharePoint 2013

A Practical Guide to SharePoint 2013
A Practical Guide to SharePoint 2013 - Book by Saifullah Shafiq

Wednesday, October 3, 2007

Invalid column name c2

SharePoint gives you this error when you try to search documents using the SPQuery object and you search by passing the document's Name. SPQuery object uses the internal field names so it's important to pass correct internal name for the correct field to be searched. By default, the "Name" field that is visible in the library has the internal name "LinkFilename" so when someone wants to search a document in the library using the "Name" field, obviously he uses the "LinkFilename" to search the document but strangely enough, it returns the following error:
"Invalid column name C2"
This error occurs in the sQL Server. SharePoint tries to search this field in the DB and returns an error when the field is not found. I haven't checked whether this field actually exists in the DB or not but we get an error. There are two more "Name" fields in the library. The internal names of the three "Name" fields are as following:
Name="LinkFilename" DisplayName="Name FieldType="Computed" -> default
Name="FileLeafRef" DisplayName="Name" FieldType="File"
Name="LinkFilenameNoMenu" DisplayName="Name" FieldType="Computed"
If you look at the definitions, you will notice that the FieldType of the two fields is "Computed" and for one field, it is "File". By default, it is the first field that is shown in the library. It has the FieldType "Computed". To search the document in the library using the "Name" field, you must use the second field that has the internal name "FileLeafRef". Although, this field is not visible in the library by default but it will return the document in the search. It's FieldType is "File" and therefore, you will have to pass the complete filename alongwith the extension in order for search to work and return the document. The third "Name" field also errors out. It is not necessary to make this field visible in the library to make the search work.
Sample query:
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='FileLeafRef'></FieldRef><Value Type='Text'>" + itemName + "</Value></Eq></Where>";
                           
SPListItemCollection listitems = list.GetItems(query);
"itemName" is the parameter that contains the file's name (passed from the interface or the calling function). It will be the complete name (alongwith extension), for example, document1.doc.


Saturday, September 8, 2007

Populating multiselect list box in InfoPath 2007 web forms programmatically

Multi select list box that comes with InfoPath 2007 does not work in web forms so you have to create your own control for usage in web forms. The following article shows you how to create a multiselect list box for web forms:
Ok, you have created a multiselect list box and now you can add static values but what if you want to populate this list box programmatically. How will you do that? The following tip shows you how you can populate this list box programmatically:
Please read the article mentioned above before continuing because without reading that article first it won't make sense to you what I am talking.
I will use the same names (for controls) as mentioned in the Microsoft article so that it's easier for you to understand what's happening. 
For your convenience, I will list the control names here:
options: is the group name
option: is the repeating group
selected: is used for the checkbox and contains true/false value
text: is a text box and is used to store the text value
Create a navigator first to navigate the xml nodes.
XPathNavigator DOM = this.MainDataSource.CreateNavigator();

"arrayItems" is an array of items retrieved from the database. Write a function that returns an array containing the items that you want to show in the multi select list box. I have not included that function here. It's a straight forward thing and not related directly to what I am trying to explain.
We will get the items from the array and add them to the list box. We will not touch the checkbox right now. We will just add the text values to the text boxes. By default, there is one row in the multi select list box. You must create new rows dynamically. Check the array length. If the lenth is 10 items, create 10 new rows. Best way is to iterate through the array and create new rows and populate the rows with the items retrieved from the array.
if (arrayItems.Length > 0)
{
       XPathNavigator Item = DOM.SelectSingleNode("/my:myFields/my:options/my:option", this.NamespaceManager);
       XPathNavigator newItemNode = null;
       for (int itemIndex = 0; itemIndex < arrayItems.Length-1; itemIndex++)
       {
              if (Item != null)
              newItemNode = Item.Clone();
              XPathNavigator navText = newItemNode.SelectSingleNode("/my:myFields/my:options/my:option/my:text", this.NamespaceManager);
                  
              navText.SetValue(arrayItems[itemIndex].ToString());
           
              Item.InsertAfter(newItemNode);
              navText = null;
              newItemNode = null;
       }
              
       Item.DeleteSelf();
       Item = null;
              
}
DOM = null;
           
Ok, so here is what I do. I create a clone of the original row and add a value to the text box of this new row.
newItemNode = Item.Clone(); // create a clone
select the text box of the newly created (cloned) row:
XPathNavigator navText = newItemNode.SelectSingleNode("/my:myFields/my:options/my:option/my:text", this.NamespaceManager);
and set it's value with the item retrieved from the array:
navText.SetValue(arrayItems[itemIndex].ToString());

Likewise, if you want to check the checkboxes programmatically, set the value of the control to boolean true or false. True will check the box, and False will uncheck the box. For example, you can check the box like this:
XPathNavigator navCheck = newItemNode.SelectSingleNode("/my:myFields/my:options/my:option/my:selected", this.NamespaceManager); 
navCheck.SetValue("true");
That's it!

Using powershell to add a policy feature to the collection

Following is the script to add a policy to the feature collection. This script will add a policy to the Records Management's feature collection. 
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Policy")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Portal")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$Url = "http://server/marketing"
$site = new-Object Microsoft.SharePoint.SPSite($Url)
#add policy to the collection
$xml = [System.IO.File]::ReadAllText("C:My Documentsfeature.xml")
[Microsoft.Office.RecordsManagement.InformationPolicy.PolicyFeatureCollection]::Add($xml)
 Similarly, to delete the policy, use following script:
[Microsoft.Office.RecordsManagement.InformationPolicy.PolicyFeatureCollection]::Delete("MarketingPolicy")
feature.xml will contain the following:
<PolicyFeature
  id="MarketingPolicy" xmlns="urn:schemas-microsoft-com:office:server:policy">
 <Name>Marketing Policy</Name>
 <Description>Marketing Policy</Description>
 <Publisher>ABC</Publisher>
 <AssemblyName>MarketingPolicy,Version=1.0.0.0,Culture=neutral,PublicKeyToken=a0231d53df8a952</AssemblyName>
 <ClassName>Marketing</ClassName>
</PolicyFeature>
Add your own assembly's information in this file (feature.xml).
See following links if you want to learn more about policies, adding policies, records management, etc:
Some more links that you may be interested in (not related to policy feature installation): 
Installing and uninstalling features using stsadm.exe:
How to create a simple feature:

Thursday, September 6, 2007

Using caspol.exe to add assemblies to full trust assembly list

Code Access Security Policy Tool (Caspol.exe) can be used to modify security policy for different policy levels. You can use it to add an assembly to the full trust assembly list for a specific policy level. Security exception is common when you try to run your application from a network share. See following article for more details:
You also get stuck sometimes when you try to deploy your application to a local folder. See following article for details:
In this tip, I will show you how you can use caspol.exe to add your assembly to a full trust assembly list.
caspol.exe is located in the following directory:
LocalDrive:WindowsMicrosoft.NetFrameworkv2.0.50727
Use the following command to put an assembly to the trust: 
caspol.exe -u -addgroup All_Code -url "*"  FullTrust -name "Your Assembly Name"
Assembly name will be like "YourCompany.ApplicationName" (without extension)
Suppose, you are deploying your application on a remote machine using a script. How will you run the caspol.exe tool on the remote machine? One way is to create a batch file and run it programmatically on the remote machine after copying the assembly to that machine. Create a batch file and copy the following in the file:
CD
PATH=%windir%microsoft.netframeworkv2.0.50727
caspol.exe -polchgprompt off -u -addgroup All_Code -url "*"  FullTrust -name "MyAssembly"
caspol.exe -polchgprompt on
polchgprompt option enables or disables the prompt that is displayed whenever Caspol.exe is run using an option that would cause policy changes. addgroup adds a new code group to the code group hierarchy. For more details, see following article:
Now, call this batch file programmatically from your deployment application.
string tempFolder = Environment.GetEnvironmentVariable("Temp");
FileStream fyle = new FileStream(tempFolder + "file://errlog.txt",FileMode.Create,FileAccess.Write/);
StreamWriter sw = new StreamWriter(fyle);
sw.Write("Ready to run the batch file!");
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents = false;
proc.StartInfo.FileName = Environment.CurrentDirectory + "\security.bat";
                  
proc.Start();
sw.Write("security.bat ran successfully!");
sw.Close();
Remember, this can be a unattended installation, so you  may want to log errors. You can log errors to the Windows log file. You can also create your own text file for logging errors, as shown in the code above. The code creates "errlog.txt" file in the Windows' Temp directory and then executes the batch file. This code does not show how to trap and log errors, you can simply use try ... catch blocks to write the errors in the text file.
Using this technique you can put assemblies to a list of full trust assemblies.

-SSA

Adding content to Word "content control" programmatically

Category: Word programming
Level: Advance 
Here is a small tip on how to add data to Word content control programmatically. If you don't know what are content controls, you can read about them at the following sites:
The articles above will give you a clear picture about content controls. The beauty of content controls is that these can be populated with data programmatically. Of course, this could be done in different ways. Following is one way of doing it:
object contentcontrolIndex;
               
contentcontrolIndex = 1; //index of content controls always start from 1, not from 0!!
               
Word.ContentControl contentcontrolSample = this.Application.ActiveDocument.ContentControls.get_Item(ref contentcontrolIndex);
contentcontrolSample.Range.InsertAfter("This is a test!"); 
"this" in third line points to the current open document. When trying this code, replace "this.Application" with your own Word reference. If you want to learn more about this topic, read the following article (VSTO 2005 SE Sample):
The code above assumes there is only one content control in the application. The index of the control will be 1. Using this technique, you can populate content controls with data retrieved from different data sources including databases and other documents.
-SSA


Adding content to Word "content control" programmatically

Category: Word programming
Level: Advance
Here is a small tip on how to add data to Word content control programmatically. If you don't know what are content controls, you can read about them at the following sites:
 http://blogs.msdn.com/microsoft_office_word/archive/2006/10/23/control-yourself.aspx
http://blogs.msdn.com/modonovan/archive/2006/05/23/604704.aspx
http://blogs.msdn.com/erikaehrli/archive/2006/08/11/word2007DataDocumentGenerationPart1.aspx
http://msdn2.microsoft.com/en-us/library/ms406053.aspx
The articles above will give you a clear picture about content controls. The beauty of content controls is that these can be populated with data programmatically. Of course, this could be done in different ways. Following is one way of doing it:

object contentcontrolIndex;
               
contentcontrolIndex = 1; //index of content controls always start from 1, not from 0!!
               
Word.ContentControl contentcontrolSample = this.Application.ActiveDocument.ContentControls.get_Item(ref contentcontrolIndex);

contentcontrolSample.Range.InsertAfter("This is a test!"); 

"this" in third line points to the current open document. When trying this code, replace "this.Application" with your own Word reference. If you want to learn more about this topic, read the following article (VSTO 2005 SE Sample):
http://www.microsoft.com/downloads/details.aspx?familyid=9331eaa4-fc4f-49e1-ac78-aa2f112d854e&displaylang=en
The code above assumes there is only one content control in the application. The index of the control will be 1. Using this technique, you can populate content controls with data retrieved from different data sources including databases and other documents.

-SSA

Tuesday, September 4, 2007

Exporting data from Access to SharePoint and Importing data into InfoPath from a SharePoint List

Category: Administration
Level: Beginner 
This beginner level tutorial will show you how you can export data from Access to SharePoint and then import data from a SharePoint list into InfoPath. Let me tell you that you can also create an InfoPath form that could access data in an external database including Access. Using a built-in wizard in InfoPath, creating such a form is very easy. You can display data from Access in the InfoPath form. You can also incorporate search feature with ease using the wizard. This tutorial is divided into parts. The first part shows how to export data to SharePoint from an Access database. 
Export data from Access to a SharePoint list.
Detailed Steps:
1.       Export Access data to a SharePoint list. Go to 'External Data' in Access and select 'SharePoint List' from the 'Export' section.
Well, honestly speaking that's the only step required. Using the wizard you can either select a pre-built SharePoint list or you can create a new one before exporting data.

Importing data from a SharePoint list into an InfoPath Form
1.       Create a new data connection in InfoPath and select following options:
a.       Create a new connection > Receive data
     
b.      Select "SharePoint library or list" option.
c.       Enter the (SharePoint) list's path where you exported the Access data.
d.      Select your list from the list of lists and libraries.
e.       Select the field (or fields) that you want to show in InfoPath.
f.        Check 'Store a copy of the data in the form template'.
g.        Add a name for the data connection and check the "Automatically retrieve data when form is opened" option.
h.      Click "Finish".
Use following steps to populate a text box with data imported from MS Access:
1.       Add a text box in your form.
2.       Right click the text box and select "Text Box Properties" to open the properties page. Enter a default value for this field (Click the button (fx) shown on the right side of the "value" text box).
      3. Click 'Insert Field or Group.' button.
      4. Select secondary data source from the 'Data source' drop down.
      5. Expand all nodes until you see field names. Select the field that you want to retrieve value from.
      6. Click OK twice and that's it!
You can use more fields to display data from different columns of the Access table.