Friday, April 15, 2011

Creating a SharePoint Solution Package (.wsp)


Step 1. Folders
First, create the folder structure for the solution. I used MySolution but you can give a name whatever you want. Two folders were created beneath MySolution - source and bin. First is for the compiled package, second – to keep the feature and the customized list. I use the same file structure for the feature as in SharePoint - one folder per feature.  Check out your SharePoint features hive at C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\DiscussionsList and see how it’s organized.
 In the source folder I made the feature folder called MyList and 2 subfolders inside - List Templates and Messages.  In the end you will have something like this:
Step 2. Building a Feature.
Here we create our feature based on the SharePoint discussions list. Go to MyList folder and create a file feature.xml, where we reference 2 files, first – list manifest  MyListManifest.xml  and the second – schema.xml  which is describing the list metadata. And don’t forget to change the GUID of feature Id with your own!
feature.xml
<?xml  version="1.0" encoding="utf-8"?>
<Feature Id="A8E6B85F-D81A-4cc1-9708-D15FEF359DE2"
    Title="My Feature"
    Description="This is my feature containing a list"
    Version="1.0.0.0"
    Hidden="FALSE"
    Scope="Web"
    DefaultResourceFile="core"
    xmlns="http://schemas.microsoft.com/sharepoint/">
    <ElementManifests>
      <ElementManifest Location="ListTemplates\MyListManifest.xml" />
      <ElementFile Location="Messages\schema.xml"/>
    </ElementManifests>
</Feature>
Copy the original schema.xml file from the C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\DiscussionsList\Discuss folder to the Messages folder, and you have a list schema to start from, MyListManifest.xml we’ll create manually in the ListTemplates folder –
MyListManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <ListTemplate
    Name="Messages"
    Type="108"
    BaseType="0"
    OnQuickLaunch="FALSE"
    FolderCreation="FALSE"
    SecurityBits="12"
    Sequence="999"
    DisplayName="My List"
    Description="This is my custom list based on the discussions list"
    Image="/_layouts/images/itdisc.gif"/>
</Elements>
What is important here is that the Name attribute must have the same name as the folder where schema.xml is placed, Messages, as SharePoint will look for the schema.xml file at that location!
After the end of this step you have 3 new files as seen on the picture
Step 3. Building a Solution Package (.wsp)
SharePoint Solution Packages (wsp ) provide a great way to distribute all your customization in just one flask and the creation of the .wsp  ain’t so painful operation as you may think, I would say it is easy as hell! Everything starts from the traditional solution manifest .xml file in the Source folder:
manifest .xml
<?xml version="1.0" encoding="utf-8"?>
<Solution xmlns="http://schemas.microsoft.com/sharepoint/"
          SolutionId="EC2EFD73-DBA2-4c0e-9C18-C8FC43F72E6C" >
  <FeatureManifests>
    <FeatureManifest Location="MyList\Feature.xml"/>
  </FeatureManifests>
</Solution>
Here, we reference our Feature.xml file that we had created before at the Step 2, and as you may guess it’s a good way to replace the the SolutionId GUID with something brand new J.  The next that should be created is the data definition file (.ddf). It’s a simple text file with the building instructions for the makecab utility because the .wsp package is nothing more than a cabinet file with the .wsp extension. (If you rename .wsp or .stp file to .cab you’ll be able to see its contents).  Let’s create a wsp.ddf in the Source folder:
wsp.ddf
.OPTION Explicit
.Set DiskDirectory1="..\bin"
.Set CabinetNameTemplate="MyListSolution.wsp"
manifest.xml
; These directory names (DestinationDir) are used for the folders creation under 12\TEMPLATE\Features
.Set DestinationDir="MyList\ListTemplates"
MyList\ListTemplates\MyListManifest.xml
.Set DestinationDir="MyList\Messages"
MyList\Messages\schema.xml
.Set DestinationDir="MyList"
MyList\Feature.xml
In this file we set an output folder for the compiled package..\bin, its name MyListSolution.wsp and we tell makecab to include 4 files (marked in red) and create 3 folders at the deployment phase (in blue). Now it’s time to build everything into a single file, but before we do that I create a build.cmd file in the Source folder with some lines to facilitate the building process
build.cmd
@setlocal
@pushd.
 @cd %~dp0
 makecab /f wsp.ddf
@popd
@endlocal
Here I reference the wsp.ddf file with processing instructions which I created before. After you run it your solution package will appear in the bin folder:
Step 4. Solution deployment.
So, the solution package has just been created and the last thing that is left to do is to deploy it to our production server. I always like then the script is doing my job, so I put 2 .cmd files into the bin folder to deploy and retract my.wsp package so I don’t have to deal with stsadm utility from command line.
 
DeployMyListSolution.cmd
@setlocal
@pushd.
@set PATH=C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN;%PATH% @cd %~dp0
 stsadm.exe -o addsolution -filename MyListSolution.wsp
 stsadm.exe -o deploysolution -name MyListSolution.wsp -local
@pause
@popd
@endlocal
RetractMyListSolution.cmd
@setlocal
@pushd.
@set PATH=C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN;%PATH% @cd %~dp0
 stsadm.exe -o retractsolution -name MyListSolution.wsp –local
 stsadm.exe -o deletesolution -name MyListSolution.wsp
@pause
@popd
@endlocal

After the solution is deployed you can activate the feature in the Site features menu of you site and start using the new list!
Step 5. Using the feature.
Before our custom list can be used the feature containing it must be activated within the SPWeb scope.
After activation is done your custom list will appear on the site’s create page and you can create list instances!

Friday, April 8, 2011

SharePoint Interview Questions

Please refer this blog
http://manomangaldas.blogspot.com/search/label/Interview

How to: combine multiple projects in one WSPBuilder Solution

We frequently use WSPBuilder to package the WSP solutions. We may need multiple projects but we need to just one WSP solution. After reading WSPBuilder documentation, I found a that "BuildSolution" command doesn't work. (or may be I have not used it properly). But I have user an alternative approach.

For an illustration, I two WSPBuilder projects and already complied:
1) SimpleWorkflow
2) SimpleEventHandler

To combine multiple projects into one WSPBuidler solution (i.e. single WSP), we have to follow these steps:

STEP1: Choose any base project such as SimpleWorkflow.
Right-click on "Solution" and choose "Add Existing Project".














STEP2: View both the projects as shown:













STEP3: Add a new deployment project. Its better to add a completely new project just for the deployment.
Right-click on "Solution" and choose "Add New Project".
































STEP4: Right click on _Deployment project, "Add New Item" >> Choose XML template and name is WSPBuilder.exe.config. (Its there from WSPBuilder documentation)

Just copy this code in WSPBuilder.exe.config


<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<appSettings>

<!-- EXISTING SETTINGS -->

<!-- As in C:\Program Files\WSPTools\WSPBuilderExtensions\WSPBuilder.exe.config -->

<!--<add key="BuildDDF" value="true" /> -->

<!-- As in C:\Program Files\WSPTools\WSPBuilderExtensions\WSPBuilder.exe.config, but value changed from 3 to 4 for more feedback -->

<add key="TraceLevel" value="4" />

<!-- MIKE'S EXTRA SETTINGS -->

<!-- The following key will ensure we build in debug mode. -->

<!--<add key="BuildMode" value="Debug" /> -->

<!-- The following key will override the wsp default of files in dev GAC dir going to the gac, and those in the bin dir going to the iis site bin directory. -->

<!--<add key="DeploymentTarget" value="GAC" /> -->

<!-- The following key will create a full 12 hive in your projects, so use only if you need all deployable folders -->

<!--<add key="Createfolders" value="True" /> -->

<!-- Don't delete intermediate files such as the manifest.xml (don't add these files to source control) -->

<!--<add key="Cleanup" value="False" /> -->

<!-- New name proposed for current BuildSolution key -->

<!--<add key="BuildMultipleProjects" value="True" /> -->

<!-- Build all projects into one solution -->

<add key="BuildSolution" value="True" />

<!-- Solution path - this tells WSP builder to step back one level for the master (startup/build) project to the main 'wsp solution'

folder, and build all projects within that folder to one wsp (cab). By default this wsp will take the name of the folder it sits

in, or use the WSPName key (see below) to give your own name. Unfortunately this dictates a rigid project folder structure, so it

is advised that projects used in more than one wsp solution solutions are subsequently 'referenced/linked' in source control to

match this client build structure rather than physically copied. They can then be 'project referenced' in Visual Studio, which

leaves the option of branching them completely if required. Although this promotes re-use, care should be taken as it often

indicates a new wsp is required to prevent inadvertent upgrades or clashes with already installed features in other solutions.

If it is a variation, consider branching or copying files (especially feature.xml to ensure guid is used), dll referencing of base

feature and inheritance. -->

<add key="SolutionPath" value="..\" />

<add key="OutputPath" value="..\" />

<add key="ExcludePaths" value="..\_Deployment\"/>

</appSettings>

</configuration>

I have also added a key "ExcludePaths" and have value of "..\_Deployment".

STEP5: Build "_Deployment", compile it, and then use this command WSPBuilder >> Build WSP.

Your ONE WSP solution with two projects included.
The only small problem is in "_Deploy" does not an option for "Deploy" using WSPBuilder.







So, we have to use STSADM commands to add solution and deploy solution.

Thursday, April 7, 2011

Object Model - SharePoint API

Please use the following URL
http://snahta.blogspot.com/2008_09_01_archive.html

**********************************************************************************
1) Open list & retrive the ListItems
 using (SPSite siteCollection = SPContext.Current.Site)
                {
                    using (SPWeb site = siteCollection.OpenWeb())
                    {
                        SPList oList = site.Lists["List Name"];
                        SPListItemCollection collListItems = oList.Items;
                        foreach (SPListItem oListItem in collListItems)
                        {}
      }
  }


==================================================
2) Set the value to People Picker

 using (SPSite site = new SPSite(SPContext.Current.Web.Site.ID))
        //    {
        //        SPUserCollection usercoll = site.RootWeb.Groups["C1st_DD"].Users;
        //        foreach (SPUser spusr in usercoll)
        //        {
        //            //groups.Add(spusr.LoginName);
        //            SetValueToPeopleEditor(spusr.LoginName);
        //        }
        //    }

OR
SPUserCollection usercoll = site.RootWeb.Groups[GroupName].Users;
private void SetValueToPeopleEditor(SPUserCollection val)
        {
            try
            {
                if (val.Count>0)
                {
                    ArrayList peopleEditorArrayList = new ArrayList();
                    for (int i = 0; i < val.Count; i++)
                    {
                        PickerEntity targetEntity = new PickerEntity();
                        if (val[i].Name != "System Account")
                        {
                            targetEntity.Key = val[i].LoginName;
                            targetEntity.IsResolved = true;
                            peopleEditorArrayList.Add(targetEntity);
                        }
                    }
                    PickerDDMembers.UpdateEntities(peopleEditorArrayList);
                   
                }
            }
            catch (Exception ex)
            {
              
            }
        }
=====================================================
3) Update UserGroup through PeopleEditor data
  protected void UpdateGroup(object sender, EventArgs e)
        {
            using (SPSite site = new SPSite(SPContext.Current.Web.Site.ID))
            {
               
                SPWeb web = site.OpenWeb();
                SPGroup memberGroup=web.Groups[SelectedGroup];
                SPUserCollection usercoll = site.RootWeb.Groups[SelectedGroup].Users;
                if (memberGroup != null)
                {
                   
                    string usersaccounts=PickerDDMembers.CommaSeparatedAccounts;
                    char[] splitter = {','};
                    string[] splituserData = usersaccounts.Split(splitter);
                    if ((memberGroup.Name != "ProgramManger".ToString()) && (memberGroup.Name != "ITSupport".ToString()) && (memberGroup.Name != "FinancialChampion".ToString()))
                    {
                        for (int j = 0; j < usercoll.Count; j++)
                        {
                            if (usercoll[j].Name != "System Account")
                            {
                                memberGroup.Users.Remove(usercoll[j].LoginName);
                            }
                        }
                        for (int i = 0; i < splituserData.Length; i++)
                        {
                            memberGroup.Users.Add(splituserData[i], "", "", "");
                        }
                    }
                    else
                    {
                        if (splituserData.Length > 1)
                        {
                            literror.Text = "Please select only one user for this group";
                        }
                        else
                        {
                            for (int j = 0; j < usercoll.Count; j++)
                            {
                                if (usercoll[j].Name != "System Account")
                                {
                                    memberGroup.Users.Remove(usercoll[j].LoginName);
                                }
                            }
                            memberGroup.Users.Add(splituserData[0], "", "", "");
                        }
                   
                    }
                }
            }
            // Go back to groups listing
            Response.Redirect(_SiteURL + "/_layouts/WHCustomerFirst/RoleGroupMgntDisp.aspx?Group=" + SelectedGroup + "&ipTitle=" + inputformTitle, true);
        }
==================================================
4) Assign the People Editor value to List
  SPSite siteCollection = SPContext.Current.Site;
                SPWeb site = siteCollection.OpenWeb();
                SPList oList = site.Lists["ListName"];
                SPListItem oListItem = oList.Items[0];
  string usersaccounts = PickerAssingedTo.CommaSeparatedAccounts;
  SPUser user = site.SiteUsers[usersaccounts];
  listItem["Assigned_x0020_To"] = AddPrincipal(oListItem, user);

 protected SPFieldUserValueCollection   AddPrincipal(SPListItem item, SPPrincipal principal)
     {
 
         SPFieldUserValueCollection fuvc = new SPFieldUserValueCollection();
         fuvc.Add(new SPFieldUserValue(item.ParentList.ParentWeb, principal.ID, principal.Name));
         //item[column] = fuvc;
         //item.Update();
         return fuvc;
 
     }
===================================================
5) Check the current logged in user belongs to Group or not

private bool IsMember()
    {
        bool isMember;
        SPSite site = SPContext.Current.Site;
        SPWeb web = site.OpenWeb();
        isMember = web.IsCurrentUserMemberOfGroup(web.Groups["Group Name"].ID);
        web.Close();
        site.Close();
        return isMember;
    }
=====================================================
6) Set the List Date value to DateTime Control
 strCompDate = oListItem["Completion Date"].ToString();
        DateTimeControlName.SelectedDate = Convert.ToDateTime(strCompDate);
====================================================
7) Insert the DateTimeControl selected date to List
 listItem["TaskDueDate"] = DateTimeControlDueDate.SelectedDate;

====================================================
8)   Renaming List Form Toolbar Items:
The following function can be used to achieve both tasks, just call the function passing the old and new names of the item. For instance if you need to rename "Add Item" to "Add Program", use renameFormMenuItems("Add Item","Add Program");. In case you need to remove the text and leave the image, call the function passing an empty string as the new name as follows: renameFormMenuItems("Delete Item","");.


renameFormMenuItems("New Item","New Program");
renameFormMenuItems("Edit Item","Edit Program");
renameFormMenuItems("Delete Item","");
function renameFormMenuItems(oldName,newName)
{
 var anchorTag;
 var allAnchorTags = document.getElementsByTagName('a');   

 if(oldName.length!=0)
 {
  for (var j = 0; j < allAnchorTags.length; j++)
  {
   anchorTag= allAnchorTags[j];   

   if (anchorTag.innerText.indexOf(oldName)!=-1)
   {                  
     
     anchorTag.innerText=newName;
     try
     {
      if(newName.length!=0)
       {             
    anchorTag.parentNode.previousSibling.firstChild.
          firstChild.alt=newName;     
      }
      else
      {
         anchorTag.parentNode.previousSibling.firstChild.
    firstChild.alt=oldName;    
      }
     }
     catch(err)
     {
     }         
   }    
  }
 }
}
==================================================
9) Get the Email address based on user AccountID
SPSite site = new SPSite(siteURL);
       SPWeb web = site.OpenWeb();
       SPUser user = web.AllUsers["Userid"];
       string email = user.Email;
==================================

10) Adding a List Item to a Custom List

using (SPWeb web = siteCollection.AllWebs["webname"])
{

SPList list = web.Lists["Custom List"];
 
SPListItem item = list.Items.Add();
 
item["Title"] = "New List Item";

item.Update();
}
=======================================
11)   Adding a List Item to a Document Library with an attachment

// Creates document in given list (root folder).
02.// Returns true if the file was created, false if it already
03.// exists or throws exception for other failure
04.protected bool CreateDocument( string sFilename, string sContentType, string sList)
05.{
06.   
try
07.   
{
08.       
SPSite site = SPContext.Current.Site;
09.

10.       
using (SPWeb web = site.OpenWeb())
11.       
{
12.           
SPList list = web.Lists[sList];
13.           
// this always uses root folder
14.           
SPFolder folder = web.Folders[sList];
15.           
SPFileCollection fcol = folder.Files;
16.

17.           
// find the template url and open
18.           
string sTemplate = list.ContentTypes[sContentType].DocumentTemplateUrl;
19.           
SPFile spf = web.GetFile(sTemplate);
20.           
byte[] binFile = spf.OpenBinary();
21.           
// Url for file to be created
22.           
string destFile = fcol.Folder.Url + "/" + sFilename;
23.

24.           
// create the document and get SPFile/SPItem for
25.           
// new document
26.           
SPFile addedFile = fcol.Add(destFile, binFile, false);
27.

28.           
SPItem newItem = addedFile.Item;
29.           
newItem["ContentType"] = sContentType;
30.           
newItem.Update();
31.           
addedFile.Update();
32.           
return true;
33.       
}
34.   
}
35.   
catch (SPException spEx)
36.   
{
37.       
// file already exists?
38.       
if (spEx.ErrorCode == -2130575257)
39.           
return false;
40.       
else
41.           
throw spEx;
42.   
}
43.}

-------------------------------------------------------------
Hide Save Button in SharePoint Survey : Please the following code in the script tag (edit the NewForm.aspx and EditForm.aspx in sharepoint desinger)

_spBodyOnLoadFunctionNames.push("setValue");
function setValue() {
hideButton("Save");
}
//This function hides a button on the page
function hideButton(valueDef){
var frm = document.forms[0];
for (i=0;i< frm.elements.length;i++) {
if (frm.elements[i].type == "button" && frm.elements[i].value == valueDef) {
frm.elements[i].style.display = "none";
}
}
}

=======================================
Add, Update and Delete List Items using C#

using (SPSite oSPsite = new SPSite("http://website/ url/"))
{
using (SPWeb oSPWeb = oSPsite.OpenWeb())
      {
            oSPWeb.AllowUnsafeUpdates = true;

            // Fetch the List
            SPList list = oSPWeb.Lists["MyList"];
                   
            //Add a new item in the List
            SPListItem itemToAdd = list.Items.Add();
            itemToAdd["Title"] = "Test Title";
            itemToAdd["Description"] = "Test Description";
            itemToAdd.Update();

            // Get the Item ID
            listItemId = itemToAdd.ID;

            // Update the List item by ID
            SPListItem itemToUpdate = list.GetItemById(listItemId);
            itemToUpdate["Description"] = "Changed Description";
            itemToUpdate.Update();

            // Delete List item
          for (int i = list.Items.Count - 1; i >= 0; i--)
                {
                    list.Items.Delete(i);
                }



            oSPWeb.AllowUnsafeUpdates = false;
       }
}