Showing posts with label Sharepoint. Show all posts
Showing posts with label Sharepoint. Show all posts

Friday, June 24, 2011

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





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, 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

Friday, November 5, 2010

Static Navigation Menu on a Site Collection

Here, I am trying to change the built-in top navigation menu with a custom made menu. These menu items are static in nature and controlled from a XML file. 


These are the steps need to be followed:


1) Create a XML file and save the file as .sitemap


< ?xml version="1.0" encoding="utf-8" ? >
< siteMap >
  < siteMapNode title="Company" url="" >
    < siteMapNode title="Profile" >
      < siteMapNode title="About Us" url="/Default.aspx" >
        < siteMapNode title="History" url="/division1/division1a/Default.aspx" >
          < siteMapNode title="Management" url="/division1/division2a/Default.aspx"/ >
        < /siteMapNode >
        < siteMapNode title="News" url="/divi/division3a/Default.aspx" >
          < siteMapNode title="Media" url="/dion1/division3a/Default.aspx"/ >
        < /siteMapNode >
      < /siteMapNode >
    < /siteMapNode >
    < siteMapNode title="Interests" >
      < siteMapNode title="Careers" url="/division1/Home.aspx" >
        < siteMapNode title="Media" url="/divisi/division1a/Default.aspx"/ >
        < siteMapNode title="News" url="/divis/division2a/Default.aspx"/ >
      < /siteMapNode >
    < /siteMapNode >
  < /siteMapNode >
< /siteMap >



2) Place the file in _app_bin directory
(eg: C:\Inetpub\wwwroot\wss\VirtualDirectories\555\_app_bin\mainmenu.sitemap)


3) Open the web.config file of the corresponding site
(eg c:\Inetpub\wwwroot\wss\VirtualDirectories\555)


4)  Look for the "< siteMap" tag, and under "< providers >" add the following entry: and save the file.


< add name="CustomXmlContentMapProvider" siteMapFile="_app_bin/CustomSiteMap.sitemap" type="Microsoft.SharePoint.Navigation.SPXmlContentMapProvider, Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" / >


5) Open the site on SharePoint Designer, and add the following inside a SharePoint:DelegateControl



     < asp:SiteMapDataSource
ShowStartingNode="true"
SiteMapProvider="CustomXmlContentMapProvider"
id="xmlSiteMap"
runat="server"/ >




6) Then look for "< SharePoint:AspMenu ID='TopNavigationMenu'
and change these:


DataSourceID="xmlSiteMap"
MaximumDynamicDisplayLevels="4" 


The MaximumDynamicDisplayLevel indicates up to how many level the menu will expand.

7) The final output will be look like this:





Thursday, October 21, 2010

Page become inactive after clicking on 'Export excel' on custom SharePoint page

Recently I faced an issue on a custom page developed on SharePoint. In this page I am showing a grid and there is a button for exporting the grid data to an excel sheet. The grid also have sorting and pagination functionalities.


After deploying the page, I learnt that, after click on 'Export to excel' link the rest of the control stops functioning. This means the data sorting and pagination links are inactive. Following codes are used for exporting:



    protected void lnkExportTop_Click(object sender, EventArgs e)
    {
        try
        {
            DataTable dtProjects = (DataTable)ViewState["Projects"];
            dtProjects.DefaultView.Sort = "MPP_Name Desc";
            gvMerge.DataSource = dtProjects.DefaultView;
            gvMerge.AllowPaging = false;
            gvMerge.DataBind();


            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader(
                "content-disposition", "attachment; filename=ProjectDashboard.xls" );
            HttpContext.Current.Response.ContentType = "application/ms-excel";

            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    //  Create a table to contain the grid
                    Table table = new Table();

                    //  include the gridline settings
                    table.GridLines = GridLines.Both;

                    //  add the header row to the table
                    if (gvMerge.HeaderRow != null)
                    {
                        PrepareControlForExport(gvMerge.HeaderRow);
                        table.Rows.Add(gvMerge.HeaderRow);
                    }

                    //  add each of the data rows to the table
                    foreach (GridViewRow row in gvMerge.Rows)
                    {
                        table.Rows.Add(row);
                    }

                    //  render the table into the htmlwriter
                    table.RenderControl(htw);

                    //  render the htmlwriter into the response
                    HttpContext.Current.Response.Write(sw.ToString());
                    HttpContext.Current.Response.End();
                }
            }
        }
        catch (Exception ex)
        {
            HandleError("Export to excel ", ex.ToString());
        }
    }

    private void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control current = control.Controls[i];
            if (current is LinkButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
            }
            else if (current is ImageButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
            }
            else if (current is HyperLink)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
            }
            else if (current is Image)
            {
                control.Controls.Remove(current);
            }
          
            if (current.HasControls())
            {
                PrepareControlForExport(current);
            }
        }
    }





Initially I thought that there is some problems with my code. But after several debugging cycle I concluded that my code is working fine.


After some researching on the net, I found that SharePoint security model basically causing the problem. Some client scripts need to call on the OnClilentClick method of the export link button.



< asp:LinkButton ID="lnkExportBottom" runat="server" Text="Export to excel" OnClientClick="_spFormOnSubmitCalled = false;_spSuppressFormOnSubmitWrapper=true;"
OnClick="lnkExportTop_Click"  / >




Hiding left blank space of Application.master in SharePoint

While developing on SharePoint once I required to use the built-in Application.master page. This master page is attached to my custom aspx page. After deployed the aspx page I noticed that, there is some blank space on the left portion of the page.

I used the following scripts to hide the left unused space and finally the page is able to use more screen space.


    < script language="javascript" type="text/javascript" >
        document.getElementById('LeftNavigationAreaCell').style.display = 'none';
        document.getElementById('TitleAreaImageCell').style.display = 'none';
        document.getElementById('onetidMainBodyPadding').style.display = 'none';
    < /script >

After adding this script the finally looks like this:


Thursday, September 2, 2010

Matching lookup column values using CAML query

To fetch items from a list based on a lookup column value, I tried the following query first.


< Query >
  < Where >
    < Eq >
        < FieldRef Name="Roadmap_x0020_Address" / >
        < Value Type="Lookup" > xyz < /Value >
   < /Eq >
 < /Where >
< /Query >


But, have not got the desired result because this query matches on the title of a lookup column, there there are cases where we can have a duplicate title. As we know that the lookup value structure is 12;#xyz, Instead of fetching by name we should look by ID


To fetch information by ID, we need use this switch LookupId=”TRUE”





< Query >

  < Where >
    < Eq >
        < FieldRef Name="Roadmap_x0020_Address" LookupId=”TRUE” / >
        < Value Type="Lookup" >12 < /Value >
   < /Eq >
 < /Where >
< /Query >

Another thing to remember is, the "FieldRef Name" we are using should be the internal name of a SharePoint column.

Friday, August 20, 2010

Programmatically complete a Workflow in SharePoint

Recently I got a requirement that some of the running workflow in a list need to be closed. I received the clear instruction that, those workflow should not be canceled and status should say 'Approved'. Basically there are some old items in the SharePoint list and these items have a running workflow associated with it. Since those list items are old, there is no point to go through a approval cycle.


After doing a impact analysis, I realized that the workflow status is depending on a task. Therefore if I close the task the associated workflow will complete automatically.


I tried the following piece of code. Here I am trying to update the task associated with the workflow programmatically.






But, to my surprise this is not working. Meaning after completing the task, the status of the workflow does not changed. The OnTaskChanged() method not called within the workflow and the status still showing 'In Progress'. I have to look for an alternative approach.


Finally, I found that the AlterTask of SPWorkflow class is correct way to update a workflow task. The following piece of code solved the purpose.





Friday, July 30, 2010

Embedding YouTube video on a SharePoint site

On the particular day, Client requested to show a YouTube video on a SharePoint site. I did a quick research and followed these steps:


On the SharePoint Site, add a 'Content Editor Webpart'. 


Next, choose 'Source Editor' from the right pane.
Now, go back to the YouTube site and find the video you want to add on the SharePoint Site. There is an Embedded button on the YouTube site, click on that to get the Embedded codes.



Now, Copy these embedded codes.


Open the Source Editor, and paste the already copied text, Save, apply and OK. 




That's all guys!!!

Tuesday, July 13, 2010

Converting office documents into a web page in SharePoint

While working on SharePoint I was looking a facility to see the uploaded documents as a web page. Then the users does not require a sophisticated office system only to view the documents.


Steps:


1) Go to Central Administration - > Operations - > Services on the Server page.

  • "Document Conversions Launcher Service"
  • "Document Conversions Load Balancer Service" should be Started.





2) Central Administration -> Application Management -> Document Conversation




3) Select the site where you want to use the Document Conversion service and Click on OK.
Please note that, this service only works on a "Publishing Site".




4) Now, go back to your site where the Document Conversion service is enabled. Hover on a document, then select "Convert Document" next, "From Word Document to Web Page". 




5) Specify the Title and URL




6) Following page shows if any errors/warning occurs at the time of conversion.




7) View the document as a web page






Limitation:

  • This service only works in a Publishing Site
  • Converts only Office 2007 documents, does not support .doc files
  • Sometimes images does not show properly on the web page.
  • Does not work if MOSS is installed on a Domain Controller.

Wednesday, June 9, 2010

Re-publish an InfoPath Template to an existing list

Recently I made a goofed-up in a SharePoint list where an InfoPath form was published. As we all know that, if we publish an InfoPath form to a library, the next time onwards the publishing wizard remember everything and you only have to click next.


But when I try to re-published a similar template from a different site to an existing library, the metadata of that list are gone. Also I have figure out that the internal names of  "Promoted Properties" are also changed. Say, earlier we have a field called "Request" now it becomes "Request1".


To avoid these type of problem, you need to map the column when published. 

Sunday, May 30, 2010

Using WSP Builder for creating and deploying a Solution

The WSP Builder is an excellent tool for creating Solution package automatically, and I am using this for a long time, so thought to write about it.

This tool is created by Carsten Keutmann and can be installed on bot VS2005 and VS2008. First you have to download from the codeplex then install.

Earlier, we had to create a "CAB Project" from the "Setup and Deployment" section on the Visual Studio. Then add the other project as resources to this CAB Project, Build the project and rename the output file extension to WSP, looks like lots of steps and efforts!!! WSP Builder is a single step creation.

Only thing need to to is Right Click on the Project of the Solution Explorer, WSPBuilder -> Build WSP

This step will generate the log that shows the components added in the WSP file created.



Important: Please verify very closely the output logs generated and check all the required DLLs are added in the WSP or not.

Once you have successfully built the WSP, now its time to deply it using STSADM commands. For this you have to navigate to the \12\BIN\ directory.

1st Command: AddSolution

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\BIN>STSADM.EXE -o addsolution -filename "E:\Project Server\Server Data\GenerateFormReceiver\EventReceiverBinder\EventReceiverBinder.wsp"
 

2nd Command: DeploySolution

STSADM.EXE -o deploysolution -name EventReceiverBinder.wsp -immediate -allowGacDeployment -url http://somu/pwa



Gotcha: The above command will give you an error "This solution contains no resources scoped for a Web application and cannot be deployed to a particular Web application."
At this point you might think there is problem in the Features.xml file, where you are trying to re-defining the scope property.

But the trick is, the DeploySolution cammand should not use a deployment scope, means the "url" switch at time moment. Therefore the solution will be globally deployed.

STSADM.EXE -o deploysolution -name EventReceiverBinder.wsp -immediate -allowGacDeployment

voilla!!! you successed.

3rd Command: ActivateFeature

STSADM.EXE -o activatefeature -name EventReceiverBinder -url http://Somu/PWA -force

And you are done.

Uninstalltion script:

Deactivate The feature:

STSADM.EXE -o deactivatefeature -name EventReceiverBinder -url http://Somu/PWA -force

Retracting the Solution:

STSADM.EXE -o retractsolution -name EventReceiverBinder.wsp -immediate

(Wait for couple of seconds...)

Deleting the Solution:

STSADM.EXE -o deletesolution -name EventReceiverBinder.wsp

 if you have not wait for the period, might encounter the following error.

The solution "EventReceiverBinder.wsp" has been deployed in the farm. Please retract the deployment before removing the solution.You can also use the -override parameter to forcibly remove the solution, but you will not be able to retract the solution deployment.

Saturday, May 22, 2010

Updating Date and Integer type fileds in InfoPath programmatically

From the title of the topic seems that this task should be easy! But to my own surprise I find it very difficult and time consuming activity.

The Task:
We are having a InfoPath form Template, that is already published in a SharePoint Form Library. Now, We have to create the InfoPath form dynamically and submit the form in the SharePoint library. This process was described earlier in this post.



Now, the problem is the InfoPath form contains certain Date and Integer data types. And I have a C# application to do the task.

First Problem:
If I have to do this task inside InfoPath managed codes using VSTA (Visual Studio Tools for Application), the following piece of can be used:

XPathNavigator root = MainDataSource.CreateNavigator();
XPathNavigator nameNode = root.SelectSingleNode("/my:myFields/my:Name", NameSpaceManager);
nameNode.SetValue("newvalue");

But, I am not using VSTA and have to navigate the XML node programmatically. The "NameSpaceManager" only available inside InfoPath managed codes only. Therefore the "NameSpaceManager should create first in the code:

public XmlNamespaceManager InitNamespaceManager(XmlDocument xmlDOMDoc)
{

XmlNamespaceManager xnmMan;
xnmMan = new XmlNamespaceManager(xmlDOMDoc.NameTable);

foreach (XmlAttribute nsAttr in xmlDOMDoc.DocumentElement.Attributes)
{
     if (nsAttr.Prefix=="xmlns")
         xnmMan.AddNamespace(nsAttr.LocalName,nsAttr.Value);
}
return xnmMan;
}

XmlNamespaceManager NamespaceManager = InitNamespaceManager(XMLDoc);


This NameSpaceManager is required to resolve any NameSpace related issues at the time of creating XPathNavigation.


Second Problem:

This problem raised when I updated the Date and Integer fields of the InfoPath file in my code. After submission of the file, when I try to open, the following error message displayed:


After googled some time, I learnt that, XML only understand a single date format. That is "yyyy-MM-dd". You have to pass the dates in this format only. So, I used:

newNode.SetValue(XmlConvert.ToString(DateTime.Now, "yyyy-MM-dd"));

Third Problem:

After putting that dates in the correct format, I was a bit confident that the problem has been resolved. But the previous error message was again shown me, i.e. "Schema validation error".

Fortunately, I got this and this on the Internet, and fixed the entire problem finally.

XmlNamespaceManager NameSpaceManager = InitNamespaceManager(XMLDoc);

XPathNavigator nav = xd.CreateNavigator();

//For a text field value
nav.SelectSingleNode("/my:myFields/my:Requestor", NameSpaceManager).SetValue("SampleData");

//For a date Field
XPathNavigator navTRDDate = nav.SelectSingleNode("/my:myFields/my:TRDDate", NameSpaceManager);

if (navTRDDate.MoveToAttribute("nil", "http://www.w3.org/2001/XMLSchema-instance"))
   navTRDDate.DeleteSelf();

navTRDDate.SetValue(DateTime.Now.ToString("yyyy-MM-dd"));

Wednesday, May 19, 2010

Generating Public Key Token in Visual Studio

The "Public Key Token" is the unique identifier for a DLL that is deployed in GAC (Global Assembly Cache). This is particularly important for me, as I need to specify that in Features.xml file for SharePoint development.


Now, getting the Public key Token is not that simple. Either you have to drag the DLL to assembly, then only you will find the Public Key Token along with the other information like Assembly Name, Version etc.


Following are the steps for generating the Public Key Token right inside the Visual Studio 2005/2008 (This screen shots are from VS 2008)


First, you need the create your Project or the Class Library, write the required coding, then sign the assembly with a key.


Secondly follow these steps, this is one time effort and can be used for n number of projects.





On the following screen you need to pass the following information
Title: A convenient title to remember
Command: C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\sn.exe
Arguments: -Tp $(TargetPath)
(note: the argument field is case sensitive)