Tuesday, December 6, 2011

Error: Your current security settings prohibit running activeX on this page

While designing a InfoPath form on Windows Server 2008 R2, received the following error message. "Your current security settings prohibit running activeX on this page". This issue was occurred when I drag a 'Contact Selector' at the time of designing a form.

First, I thought to minimize the IE security permission level. But that action was not helped at all. Then I found this blog to disable Internet Explorer Enhanced Security Configuration.
 The final output: the 'Contact Select' is working fine.

Wednesday, November 9, 2011

Silverlight webpart in SharePoint 2010

Foolowing are the steps for creating a silver light webpart for SharePoint 2010.

1) Create a new project with the template "Silverlight Application"
2) Un-check "Host the Silverlight application in a new web site.
3)  Add the following references from this path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin".
Microsoft.SharePoint.Client.Silverlight.dll
Microsoft.SharePoint.Client.Silverlight.Runtime.dll

4) Add this reference as well System.Windows.Controls.Data.Input
5) After adding the reference, the solution pane should look like this:

6) Next step is to design the XAML:
< UserControl x:Class="SilverlightApplicationHelloWorld.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:datainput="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" >
    < Grid x:Name="LayoutRoot" Background="White">
        < Button Click="btnLoadSite_Click" Content="Load Site" Height="23" HorizontalAlignment="Left" Margin="25,12,0,0" Name="btnLoadSite" VerticalAlignment="Top" Width="75" >< /Button >
        < Canvas Name="canvasLabels" Visibility="Collapsed" >         
            < datainput:Label Content="Site: " Height="22" HorizontalAlignment="Left" Margin="41,55,0,0" Name="label1" VerticalAlignment="Top" Width="73" >< /datainput:Label >
            < datainput:Label Height="22" HorizontalAlignment="Left" Margin="120,55,0,0" Name="label2" VerticalAlignment="Top" Width="233" >< /datainput:Label >
            < datainput:Label Content="Url:" Height="24" HorizontalAlignment="Left" Margin="41,84,0,0" Name="label3" VerticalAlignment="Top" Width="73" >< /datainput:Label >
            < datainput:Label Height="24" HorizontalAlignment="Left" Margin="120,84,0,0" Name="label4" VerticalAlignment="Top" Width="233" >< /datainput:Label >
            < datainput:Label Content="Description" Height="26" HorizontalAlignment="Left" Margin="41,116,0,0" Name="label5" VerticalAlignment="Top" Width="73" >< /datainput:Label >
            < datainput:Label Height="26" HorizontalAlignment="Left" Margin="120,116,0,0" Name="label6" VerticalAlignment="Top" Width="233" >
             < /datainput:Label >
        < /Canvas >
    < /Grid >
< /UserControl >

7) Add the following in code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.SharePoint.Client;
namespace SilverlightApplicationHelloWorld
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }
        private ClientContext context = null;
        private Web web = null;
        private delegate void UpdateUIMethod();
        private void btnLoadSite_Click(object sender, RoutedEventArgs e)
        {
            context = ClientContext.Current;
            web = context.Web;
            context.Load(web, w => w.Title, w => w.Description, w => w.ServerRelativeUrl);
            context.ExecuteQueryAsync(OnSiteLoadSuccess, OnSiteLoadFailure);
        }
        private void OnSiteLoadSuccess(object sender, ClientRequestSucceededEventArgs e)
        {
            UpdateUIMethod updateUI = LoadSiteData;
            this.Dispatcher.BeginInvoke(updateUI);
        }
        private void OnSiteLoadFailure(object sender, ClientRequestFailedEventArgs e)
        {
            MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
        }
        private void LoadSiteData()
        {
            canvasLabels.Visibility = System.Windows.Visibility.Visible;
            label2.Content = web.Title;
            label4.Content = web.ServerRelativeUrl;
            label6.Content = web.Description;
        }
    }
}
8) For deployment there are two steps:
8a) Directly deploy to "Client Bin" folder.
Change the "Output Path" to "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin" in the Solution -> Property page.
Now, add a Silverlight webpart on a sharepoint page and set the URL as
"_layouts/ClientBin/SilverlightApplicationHelloWorld.xap". 
 
8b) Other approach is add the XAP to a document libratry, and give the path in Silverlight webpart

Wednesday, November 2, 2011

Accessing Lists.asmx

I Got a requirement to access a list data through web service. Therefore, I consumed 'Lists.asmx' built-in service provided by SharePoint.


1) Following codes are required to get list item through CAML query

            Lists listService = new Lists();
            listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
            listService.Url = "http://spsserver" + "/_vti_bin/lists.asmx";
            XmlDocument xmlDoc = new System.Xml.XmlDocument();
            XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
            XmlNode ndViewFields =
                    xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
            XmlNode ndQueryOptions =
                    xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");


            ndViewFields.InnerXml = "";
            ndQuery.InnerXml = "" +
                                "0";
            try
            {
                XmlNode ndListItems = listService.GetListItems("Tasks", null, ndQuery, ndViewFields,null, null, null);
                foreach (System.Xml.XmlNode listItem in ndListItems.ChildNodes[1].ChildNodes)
                {
                    if (listItem.OuterXml.Contains("ows_Title"))
                    {
                        txtValue.Text += Environment.NewLine + listItem.SelectSingleNode("@ows_Title").Value.Trim();
                        string strStartDate= listItem.SelectSingleNode("@ows_StartDate").Value.Trim();
                        DateTime dtConvert = DateTime.SpecifyKind(DateTime.Parse(strStartDate), DateTimeKind.Utc);
                        txtValue.Text += "  " + dtConvert.ToLocalTime().ToString();
                    }
                }
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                MessageBox.Show("Message:\n" + ex.Message + "\nDetail:\n" +
                    ex.Detail.InnerText +"\nStackTrace:\n" + ex.StackTrace);
            }
2) This code is for updating a list item through batch update
            try

            {
                string strBatch = " 2" +
                                       "a test data";
                XmlDocument xmlDoc1 = new System.Xml.XmlDocument();
                System.Xml.XmlElement elBatch = xmlDoc1.CreateElement("Batch");
                elBatch.SetAttribute("OnError", "Continue");
                elBatch.SetAttribute("ListVersion", "1");
                elBatch.InnerXml = strBatch;
                XmlNode ndReturn = listService.UpdateListItems("Tasks", elBatch);
                MessageBox.Show(ndReturn.OuterXml);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

Saturday, September 24, 2011

Fixing issue "Access denied by Business Data Connectivity"

While working with BCS I have encountered an issue "Access denied by Business Data Connectivity"
Here, I was creating one external content type with a connection to a SQL server database. Please follow this blog to create such list.
After creating a SharePoint list, when I am trying to open it on the browser, following error is generated. 

 To Fix this issue, on the Central Administration, modify service application and grant permission to the BCS data connections. Please follow these steps: 




Now, the correct result is showing like this:

Wednesday, August 24, 2011

Delegate control in SharePoint

SharePoint offers a fine way to override it's built-in functionality. With the help of delegate control you do not required to modify the existing master page to modify existing features.

First, create a empty SharePoint project, and specify the target web url. Next select 'Farm Solution' a deployment option. Now add one User Control in the SharePoint mapped folder 'Control Templates'. Add functionality to this user control based on the requirements.
Now, create one element file, and add the following xml.
< ?xml version="1.0" encoding="utf-8"? >
< Elements xmlns="http://schemas.microsoft.com/sharepoint/" >
  < Control Id="GlobalNavigation"
           Sequence="10"
           ControlSrc="~/_ControlTemplates/SampleTestNavigation/TestNavigation.ascx"/ >
< /Elements >


Here, GlobalNavigation control defined in the master page will be overridden by this custom control. The Sequence value should be less than 100. 


Deploy the solution. And the output will be look like this:

Sunday, August 21, 2011

Creating UDC in InfoPath forms

During development there is common requirement is to create InfoPath forms, those can be deployed into multiple servers. Once you completed the development in local DEV, the forms need to deploy in Stage and Prod. Here an issue arises, the connection. Since the path of different servers are different one need to create 'Universal Data Connection' (UDC) 


1) Create a connection for submit data, and follow the wizard

2) Create a Connection Library, then click on the 'Convert' button, this will generate one XML file. Specify a name of the connection with extension UDCX

3) After creating the UDCX file, on the InfoPath form, add a new connection and browse all the connections on the server.

4) Important, for each server, Staging, Prod etc you have to create data connection file with the same name. In this example submit.udcx. The forms will pick dynamically the connection based the respective servers.




Friday, July 15, 2011

Sharepoint 2010 Timer Service error code 1069

On my local SharePoint server, Timer Service gives me an error "The service could not be started due to logon failure".


Initially I thought that, there is a need to enable some service from the Central Administration. Later realized that the issue is in the service itself.
The issue is fixed after setting of proper password within the service properties.


Thursday, July 7, 2011

Fixing error "Cannot generate serialization assembly"

Recently on my development machine I faced this error in Visual Studio. The error occurred at the build a project, and that project is already in use on the local machine.
Now, the problem here is, out the error message nothing clearly come out. After further research I found that the output dll is already present in GAC and after removing that dll, the project showed successful build.


Cheers!!
Somu

Friday, June 24, 2011

Shrink Database

While working with MOSS and Project Server I noticed the physical hard disk size is growing rapidly and captured a lot of space. After opening the database files I found the DB log file taking huge space. 
 (Before)


Following Database script is executed on SQL Server to Shrink the size of the log files. It is very effective to reduce the size.
USE XXX_MOSS_Config
GO
ALTER DATABASE XXX_MOSS_Config SET RECOVERY SIMPLE
DBCC SHRINKFILE(N'XXX_MOSS_Config_log', 1)
ALTER DATABASE XXX_MOSS_Config SET RECOVERY FULL
GO

 (After)
Cheers!!!

Creating Custom Application Pages in MOSS

On a development cycle, you might need to create several custom Application Pages, which will be stored in Layouts\FolderName\YourPage.aspx.


While creating the page the base class need to inherit is "LayoutsPageBase"
Here is a blog specified about the steps for creating the pages.


Now, the challenge is, when you create such Application page for Anonymous Access, the user  asked for a log in. Means the Anonymous user redirected to the login page. 


To avoid such scenario, there is another base class need to inherit "UnsecuredLayoutsPageBase"
The code of the page will look like this:

protected partial class CustomPage : UnsecuredLayoutsPageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
}
On the same page, following method also need to be added for smooth functioning:
protected override bool AllowAnonymousAccess
{
   get
   {
       return true;
   }
}
Cheers!!
Somu





Monday, May 2, 2011

Read Project Server Custom Fields value from the database

There is a standard method of accessing Project Server data and Custom Fields information. That is create web service reference with PSI. Recently I have created a report of Projects with custom field values with some business requirements. Now, the the loading time of the report is very high and that is causing huge dissatisfaction.
After some searching I found a Project Server database view, which contains all the project information with custom fields values. The name of the view is  MSP_EpmProject_UserView  and it is present in Reporting DB. 



Once you are able to find the view, then you can write query according to your needs.
Cheers,
Somu

Friday, April 29, 2011

Custom ASPX page and automatic deployment in SharePoint

For a particular project, I was required to built a couple of custom pages and deploy them with a WSP.


For the solution, we first need to create a Class Library project. First, create a folder structure from 12 hive, as shown below. Under layouts folder, place the ASPX pages. Then I add a folder named "ApplicationPages" and add the code behind C# files.
The Folder "ApplicationPages" is required, otherwise we can also have a folder name as "FeatureCodes". These are names that SharePoint understand well.

Next, for each of the code behind C# files, a common Namespace has been set and a separate class name is defined.
And on the ASPX page, we need to specify the assembly info. For that the project need to sign with a string name, then built and finally get Public Key Token with a tool. Here is my blog for easy retrieval of Public Key Token. 

On each of ASPX page, we have to set the Assembly info, Public key token in the page directive area.

After that, build the project, and create a WSP using WSP builder. Finally deploy the WSP with a STSADM command.


Cheers...
Somu

Tuesday, March 22, 2011

An unhandled exception ("System.MissingMethodException") occured in "ApplicationName" [22956]

In my day to day development work I faced this issue today. I am having a Class Library with several methods in it. This class library also takes several web service references. Now, I created a Console Application and take the assembly reference of this class library. And when I tried to run the Console Application, following error message is generated: 
An unhandled exception ("System.MissingMethodException") occured in "ApplicationName" [22956]


I got no clue after reading this message, since it is a very generic error message. I deleted the assembly reference and restarted the Visual Studio a couple of times. But no luck, the problem remains the same.


After following a reference on the net, I learnt that the Class Library I created should have at least one default constructor. Otherwise you may get this kind of ambiguous error message.


It saved my day!!!

Monday, February 28, 2011

File Not Found exception on SharePoint 2010

There is a common practice of SharePoint Development is to create a windows or console application to fetch several SharePoint data. This method is widely used because there is no deployment steps to perform. The only limitation of using such application is, you have be on the SharePoint Server.


While trying to access to list information of a SharePoint 2010 site, I used a windows application to fetch data. To my surprise, I am getting a "File not found" exception. But the same code working perfectly fine in MOSS 2007


It's a very wired message, as I am not trying any file operation. And the message forced me to searched on the web several hours. And finally understood that the issue is in the build configuration. 
By default the compilation is in 32 bit (86x), this need to be changed to "Any CPU".
That's all. After this changes my code is working fine.


Tuesday, February 22, 2011

Fixing issue "Cannot connect to the configuration database"

One day on my Dev machine I received the following error while browsing my site. 


The I searched on the Google and find out this Microsoft KB article and followed each steps. Though it was written for WSS 2.0 but it's working fine for WSS 3.0 and MOSS. But following those steps does not helped much. 
While working on SQL Database, I found a wired thing that is SharePoint_Config Db is marked as 'Suspect'.
  


After further research, I found this blog to use the DB script to restore it back to the original condition.


EXEC sp_resetstatus 'DBname'
ALTER DATABASE DBname SET EMERGENCY
DBCC checkdb('DBname')
ALTER DATABASE DBname SET SINGLE_USER WITH ROLLBACK IMMEDIATE
DBCC CheckDB ('DBname', REPAIR_ALLOW_DATA_LOSS)
ALTER DATABASE DBname SET MULTI_USER



Final Issue: At the time of using this script I am getting sql error. Incorrect syntax near '-'. This error causing by the illegal characters in the DB name. As SharePoint adds GUID in the title of SharePoint config database.


We need to use a [bracket] for handling such issues. This Microsoft site got details about it.
use [SharePoint_AdminContent_d610f804-ebc5-4480-91a8-1f0a53de078a]



Tuesday, February 8, 2011

Common scenarios in Web Services of SharePoint 2007

Following are the common Web Services available in a SharePoint 2007. The physical location of these files is "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI"



Administration Service             http:///_vti_adm/admin.asmx 
Alerts Service                          http:///_vti_bin/alerts.asmx 
Document Workspace Service   http:///_vti_bin/dws.asmx 
Forms Service                          http:///_vti_bin/forms.asmx 
Imaging Service                        http:///_vti_bin/imaging.asmx 
List Data Retrieval Service        http:///_vti_bin/dspsts.asmx 
Lists Service                            http:///_vti_bin/lists.asmx 
Meetings Service                      http:///_vti_bin/meetings.asmx 
Permissions Service                  http:///_vti_bin/permissions.asmx 
Site Data Service                      http:///_vti_bin/sitedata.asmx 
Site Service                             http:///_vti_bin/sites.asmx 
Users and Groups Service           http:///_vti_bin/usergroup.asmx 
Versions Service                       http:///_vti_bin/versions.asmx 
Views Service                          http:///_vti_bin/views.asmx 
Web Part Pages Service            http:///_vti_bin/webpartpages.asmx 
Webs Service                           http:///_vti_bin/webs.asmx 





Setting the web service user credentials
The SharePoint web services only accept calls from existing SharePoint users and do also enforce access security. Import the System.Net namespace into your project and then use the NetworkCredential class to set the user credential to use for the web service call. Here is a code snippet:


public static XmlNode VersionsGetVersions(string SharePointHost, string UserName,
                              string Password, string Domain, string FileName)
{
// proxy object to call the Versions web service
Versions.Versions VersionsService = new Versions.Versions();


// the user credentials to use
VersionsService.Credentials = new NetworkCredential(UserName, Password,
Domain);
VersionsService.Url = SharePointHost + “_vti_bin/Versions.asmx”;


// gets the file versions
XmlNode Result = VersionsService.GetVersions(FileName);


// dispose the web service object
VersionsService.Dispose();
return Result;
}


Following are some real life example of using SharePoint Web Services:



Example 1:  Get the collection of SharePoint lists, fields and views 
In the first example we want to get the collection of SharePoint lists. For each list we want to get all the defined list fields (fields you can use to store information) and finally all views associated with the list. Here are the web methods to call:


1) On the Lists web service call the GetListCollection() web method to get the collection of all SharePoint lists. This returns an XML document with all SharePoint lists. 
2) Next you run the “//sp:List” XPath query to get all matching List nodes. The Title attribute of each matching node contains the name of the SharePoint list. 
3) For each SharePoint list we call the GetList() web method on the Lists web service, passing along the list name. This returns a XML document with detailed information about the list including the list of fields. 
4) Next you run the “//sp:Field” XPath query to get all the matching Field nodes. The Name attribute contains the field name. 
5) For each SharePoint list we call the GetViewCollction() web method on the Views web service, passing along again the list name. This returns a XML document listing all views for the list. 
6) Finally you run the “//sp:View” XPath query to get all the matching View nodes. The Name attribute contains the name of the view. 


Example 2:  Get the list of users and site-groups
In this example we want to get the list of site users and to which site group each user belongs. We also want to get the list of site groups and which users belong to each site group.


1) On the Users-and-Groups web service we call the GetUserCollectionFromWeb() web method. This returns an XML document with all the site users. 
2) Next you run the “//d:User” XPath query to get all the matching User nodes. The Name attribute contains the user name and the LoginName attribute the user's login name. 
3) For each user we call the GetRoleCollectionFromUser() web method on the Users-and-Groups web service passing along the user's login name. This returns a XML document with all the site groups the user belongs to. 
4) Next you run the “//d:Role” XPath query to get all the matching Role nodes. The Name attribute contains the site group name. 
5) To get the list of site groups call the GetRoleCollectionFromWeb() web method on the Users-and-Groups web service. This returns an XML document with all site groups. 
6) Next you run again the “//d:Role” XPath query to get all the matching Role nodes. The Name attribute contains the site group name. 
7) Finally call for each site group the GetUserCollectionFromRole() web method on the Users-and-Groups web service passing along the site group name. This returns an XML document with all the users belonging to this site group. 
8) Next you run again the “//d:User” XPath query to get all the matching User nodes. The Name attribute contains the user name and the LoginName attribute the user's login name. 


Example 3:  Get the list of sites, site-templates and list-templates
With the last example we want to get a list of all sites in the site collection. We want to get for the site collection the list of site templates. Additionally we want for each site the list of list templates.


1) First we call the GetAllSubWebCollection() web method on the Webs web service. This returns an XML document with all sites in the site collection. 
2) Next run the “//sp:Web” XPath query to return all matching Web nodes. The Url attribute contains the absolute URL for the site. 
3) Then we call the GetSiteTemplates() web method on the Sites web service. This returns an array of available site templates in the site collection, which is an array of the type Sites.Templates. The attached sample application converts all structures to an XML document using reflection, so you can run XPath queries against it (see the method SharePoint.SitesGetSiteTemplates()). 
4) Next run the “//SharePointServices.Sites.Templates” XPath query which returns all matching template nodes. The Title attribute contains the template title and the Name attribute the SharePoint template name. 
5) For each site we call the GetListTemplates() web
method on the Webs web service. Before calling the web service object you need to set the URL to the site URL (returned by GetAllSubWebCollection()). This way we make sure that the call is to the site itself and returns the list templates of that site. This returns an XML document with all list templates. 
6) To finish run the “//sp:SiteTemplate” XPath query to return all matching SiteTemplate nodes. The DisplayName attribute contains the name of the list template.





Thank you,
Soumyendra

Sunday, January 30, 2011

Impersonation in Event Receiver

Recently faced an issue while working with Event Receivers. That is, current user need to impersonate with higher privilege account. Normally we do that with application pool account. 


Th problem here is, if you try to use event receiver's 'property' object to access the current web or the list item, the impersonation never works there. For example, following piece of code will use current user credentials, not the application pool account permission.


SPSecurity.RunWithElevatedPrivilege(delgate
{
properties.ListItem.Delete();
});


For using impersonation, you need to create a separate instances of SPWeb, then access your items.



SPSecurity.RunWithElevatedPrivilege(delgate
{
  using(SPSite site = new SPSite(properties.WebUrl))
  {
     using(SPWeb web = site.OpenWeb())
     {
         //access your items here.
     }
  }
});