Sharepoint Insight by Namwar Rizvi

Sharepoint Tips, Tricks and inside knowledge from real world experience by Namwar Rizvi

Posts Tagged ‘Utility Functions’

Reverse Engineer the Schema of any List in SharePoint

Posted by namwar on December 26, 2009


If you have ever designed a custom list then you may already felt the pain of creating the schema of it and writing the whole CAML. Sometimes, we just need to enhance an already existing list by creating our own custom list for which we want to copy the existing schema and do the necessary changes.

You can retrieve the schema of any list by using the owssvr.dll call from your browser. Following is the syntax

http://<YourServer>/_vti_bin/owssvr.dll?Cmd=ExportList&amp;List=<YourListGuid>&#8221;

By replacing the Server and List GUID in above url will return you the XML Schema of the list.

To make thing easier, I have created a Feature to add a custom action in Settings menu called “Display Schema“, Click it and you will get the schema of the list.

Steps to create the feature:

1. Create a new folder called “DisplaySchema” in Features folder.

2. Create Feature.xml file and paste the following code

<?xml version="1.0" encoding="utf-8" ?>
<Feature Id="{A66E6CBA-8EA1-4c28-B233-52B3D7FF352B}"
    Title="Display List Schema"
    Description="This feature adds a custom menu item in Settings menu to display List Schema"
    Version="1.0.0.0"
    Scope="Site"
    xmlns="http://schemas.microsoft.com/sharepoint/">
  <ElementManifests>
    <ElementManifest Location="Elements.xml" />
  </ElementManifests>
</Feature>

3. Create Elements.xml file and paste the following code

<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<!-- List Toolbar Settings Menu Dropdown -->
  <CustomAction Id="DisplayListSchema"
    RegistrationType="List"
    GroupId="SettingsMenu"
    Location="Microsoft.SharePoint.StandardMenu"
    Sequence="1000"
    Title="Display Schema"
	Description="Displays schema of the list">
    <UrlAction Url="~site/_vti_bin/owssvr.dll?Cmd=ExportList&amp;List={ListId}"/>
  </CustomAction>
</Elements>

4. Install the feature by using stsadm command line tool.
5. Activate it.
6. Navigate to any list, Document Library, Tasks list etc. and click Settings, and then click Display Schema.
You will get the schema of that list. Copy it and enjoy!

Advertisements

Posted in Customization, Feature, Solutions, Tips, Tools | Tagged: , , , | 2 Comments »

Visual Studio 2008 extensions for Windows SharePoint Services 3.0, v1.3 – Mar 2009 CTP

Posted by namwar on March 24, 2009


A goow news for SharePoint community 🙂 Microsoft has releasesd the Mar 2009 CTP of Windows SharePoint Services 3.0 v1.3. This CTP contains excellent set of functionalities and saves your precious time. You can download the extensions from here

Following is the overview as released by Microsoft

This is the SharePoint developer tools for Visual Studio 2008. These tools are suitable for use with Windows SharePoint Services 3.0 or Microsoft Office SharePoint Server 2007. It includes project and item templates for common SharePoint artifacts, it includes build, packaging and deployment for SharePoint solutions and it includes the SharePoint Solution Generator which creates a new Visual Studio 2008 project from a SharePoint site.

The tools provide item templates for List Definition, List Definition from Content Type, Content Type, Field Control, Web Part, Module, Root File, Template, Event Receiver, and List Instance. It provides project templates for Team Site Definition, Blank Site Definition, List Definition, Web Part and Empty. It works with Visual Basic .NET and C# languages and a comprehensive user guide is included. It does not include the SharePoint Workflow templates as they are built in with Visual Studio 2008.

New features in version 1.3 include:

  • Can be installed on x64 Server OS machines running SharePoint x64. Previously only x86 Server OS could be used
  • Separate build commands for package, deploy and retract are added as Visual Studio menu items
  • WSP View improvements for consistency of deleting feature elements, merging features and adding event receivers to features
  • Command line build, package and retract commands are included enabling continuous integration and build servers. Previously command line build of SharePoint projects was very difficult
  • Refactoring support for renaming of Web Parts. Previously renaming a web part required changes in several files in the project
  • Solution Generator can now generate solutions from publishing sites. Previously only regular sites could be generated
  • Allowing partial trust BIN deployments of web parts
  • New project item template for SharePoint RootFiles items
  • Deployment will now optionally remove conflicting existing features on the development server prior to redeployment. Previously any feature name conflicts would result in an error
  • Ancillary assemblies such as for business logic can now be added to the SharePoint Solution WSP
  • Hidden features related to Site Definition projects are now shown in WSP View. They are no longer hidden
  • For advanced users a fast deploy is included to update only the compiled assembly on the SharePoint development installation
  • Deployment step logging is included
  • The List Definition from Content Type template now allows for the creation of a List Definition Event Receiver
  • The User Guide is now installed with the extensions instead of being a separate download

Posted in Debugging, Guidance, Templates, Tools | Tagged: , , , , , , , , | Leave a Comment »

Launch Office Application from SharePoint Portal Page

Posted by namwar on February 26, 2009


Business Problem:

    One of my client wanted to have links on main portal to launch Microsoft Office key applications i.e Word, Excel, Power Point and Outlook directly by clicking on a link at portal page.

Solution:

I searched the net and find a nice solution here It is a small piece of JavaScript code which you can put in CEWP and use it on your portal page. I added some formatting and relevant icons against the office applications and wraps it up in a webpart dwp file. After importing this web part on your page, you will get something like this:

launchofficeapplication1

You can download the dwp file from here

Posted in Customization, JavaScript, Uncategorized | Tagged: , , , , | 3 Comments »

Verify your code with SharePoint Dispose Checker Tool

Posted by namwar on February 2, 2009


Today, a new tool  SharePoint Dispose Checker Tool  has been released at MSDN for checking your code against incorrect processing of IDisposable objects like. SPSite and SPWeb. This tool checks your assembly and identify potential problems of not disposing these objects. 

You can download SharePoint Dispose Checker Tool from here

and here is the great article from Paul Andrew (Microsoft Technical Product Manager for the SharePoint Developer Platform) about best practices and how to use this tool.

Posted in Bugs, Debugging, Object Model, Tools | Tagged: , , , , , , | Leave a Comment »

Programmatically upload a file to Document Library

Posted by namwar on January 10, 2009


Following is a utility function which you can use to upload a file programmatically in SharePoint document library. It has two parameters. First is the source file path and second is the target document library path. 

Following is an example call to this function:

UploadFileToDocumentLibrary(@”C:\test.txt”, @”http://home-vs/Shared Documents/textfile.txt”);

and here is the function

    public static bool UploadFileToDocumentLibrary(string sourceFilePath, string targetDocumentLibraryPath)

    {

        //Flag to indicate whether file was uploaded successfuly or not

        bool isUploaded = true;

        try

        {

            // Create a PUT Web request to upload the file.

            WebRequest request = WebRequest.Create(targetDocumentLibraryPath);

 

            //Set credentials of the current security context

            request.Credentials = CredentialCache.DefaultCredentials;

            request.Method = “PUT”;

 

            // Create buffer to transfer file

            byte[] fileBuffer = new byte[1024];

 

            // Write the contents of the local file to the request stream.

            using (Stream stream = request.GetRequestStream())

            {

                //Load the content from local file to stream

                using (FileStream fsWorkbook = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read))

                {

                    //Get the start point

                    int startBuffer = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length);

                    for (int i = startBuffer; i > 0; i = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length))

                    {

                        stream.Write(fileBuffer, 0, i);

                    }

 

                }

            }

 

            // Perform the PUT request

            WebResponse response = request.GetResponse();

 

            //Close response

            response.Close();

        }

        catch (Exception ex)

        {

            //Set the flag to indiacte failure in uploading

            isUploaded = false;

        }

 

        //Return the final upload status

        return isUploaded;

    }

Posted in C# | Tagged: , | 12 Comments »

SPDiffUtility: An excellent class to find differences in strings with HTML highlighting

Posted by namwar on August 25, 2008


While exploring Sharepoint utility classes, I found an excellent class which deserve more credit then it currently enjoys. It is SPDiffUtility. This class has only one static method called Diff which determines the text differences between two strings. It takes three parameters:

  1. str1: The original string
  2. str2: The changed string
  3. maxDifferences: A 32-bit integer representing the maximum number of differences to find.

The beauty of this function lies in its return value which is a merged version of the specified strings that contain HTML tags indicating inserted, deleted, or changed text.

This returned string contains HTML tags to highlight the changes, insertions and deletions. The best part is that you can set these tags with your HTML tags if you want. Following is the sample usage of this class.

  1. Create a web site project in Viusal Studio
  2. Add reference to Microsoft.Sharepoint.dll found in C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\Microsoft.SharePoint.dll
  3. Paste the following code in Default.aspx
  4. <%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
    <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
    <html xmlns=”http://www.w3.org/1999/xhtml”&gt;

    <head runat=”server”>
    <title>Untitled Page</title>
    </head>

    <style type=”text/css”>
    .ms-diffdeletenostrike {
    BACKGROUND-COLOR: #e0e0e0;
    }
    .ms-diffdelete {
    BACKGROUND-COLOR: #e0e0e0;
    }
    .ms-diffdelete {
    TEXT-DECORATION: line-through;
    }
    .ms-diffinsert {
    BORDER-RIGHT: #ffffff 1px solid;
    BORDER-TOP: #ffffff 1px solid;
    = BORDER-LEFT: #ffffff 1px solid;
    BORDER-BOTTOM: #ffffff 1px solid;
    = BACKGROUND-COLOR: #ffeaad;
    }
    </style>
    <body>

    <form id=”form1″ runat=”server”>
    <div>
    <asp:Label ID=”lblResult” runat=”server” Text=””></asp:Label>
    </div>
    </form>

    </body>

    </html>


  5. Open Default.aspx.cs and paste the following code

  6. using System;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    using Microsoft.SharePoint.Utilities;
    using System.Diagnostics;

    public partial class _Default : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    string firstString = “This is an initial string”;
    string secondString = “This”;

    //Set the tags
    SPDiffUtility.ChangeOpenTag = ““;
    SPDiffUtility.ChangeCloseTag = “
    “;
    SPDiffUtility.InsertOpenTag = ““;
    SPDiffUtility.InsertCloseTag = “
    “;
    SPDiffUtility.DeleteOpenTag = ““;
    SPDiffUtility.DeleteCloseTag = “
    “;

    //end setting tags

    //Find the difference
    string diffString = SPDiffUtility.Diff(firstString, secondString, Int32.MaxValue);
    lblResult.Text = diffString;

    }
    }

  7. Run web application by pressing Ctrl+F5

You will see “This is an intial string where striked out letters are those which have been deleted in the second string.

Posted in Object Model | Tagged: , | 2 Comments »