Loading...

Monday, December 5, 2011

Sharepoint Client Object Model:Working with Survey List and debugging ECMA Script

The List Schema for Survey List is quite different from the Custom Lists.
Every Question is added as the List column(Field)  and
Every Response to questions is added as   List Item.
To retrieve the Survey question and and To submit the response to List via Client Object Model,
do the following.


1)Load the reference of sp.js  and Load the address of function to be called as below
SP.SOD.executeOrDelayUntilScriptLoaded(DisplaySurveyQ,'SP.js');
2)Define the function.
var surveyItems = null;
var surveyFields=null;
var surveyList = null;
var oneField = null;

function DisplaySurveyQ()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
// of your desired target list:
surveyList = web.get_lists().getByTitle('surveylistName');
//alert(surveyList);
var caml = new SP.CamlQuery();
surveyItems = surveyList.getItems(caml);
surveyFields=surveyList.get_fields();
oneField = surveyFields.getByInternalNameOrTitle("Title"); 
//alert(surveyFields);
//alert(surveyItems);

//listOperations
context.load(oneField);
context.load(surveyList);
context.load(this.surveyItems);
context.load(this.surveyFields);  


context.load(list);
alert(list);

3) Create callback handlers in this function
var success = Function.createDelegate(this, this.onSuccess);
var failure = Function.createDelegate(this, this.onFailure);

4)Execute an async query in this function
context.executeQueryAsync(success,failure);
}

5)Define  Function On  success full operation.
// Async query succeeded.
function onSuccess(sender, args) {
// for example iterate through list items or fields and assign the value to  html controls like  div, uls etc
var listEnumerator = surveyItems.getEnumerator();
var listFieldEnumerator = surveyFields.getEnumerator();
var Fields=surveyList.get_fields();
var Questions=new Array();
var qCount=0;
//iterate though all of the Questions  and get the recently added question from Survey
var Count=0;
while (listFieldEnumerator .moveNext()) {
var currentField=listFieldEnumerator.get_current();
//alert(currentField.get_fieldTypeKind());
if(currentField.get_fieldTypeKind()==SP.FieldType.choice)
{
//alert(currentField.get_title());
Questions[qCount]=currentField;
}
Count= Count+ 1;
}
var currentField=Questions[qCount];
var FieldsChoices=currentField.get_choices() ;
 

// save the current questions internal name in hidden field , which will be helpful while submitting the response.
input type='hidden' name='CurrentQuestion' id='CurrentQuestion' value='"+currentField.get_internalName()

var divSurvey='generateRequiredHtml'
document.getElementById('generateRequiredHtmlandAssignThisIDmustPresent').innerHTML =divSurvey ;

}


6)Pass on the exception to UI by defining the failure function
// Async query failed.
function onFailure(sender, args)
{
alert(args.get_message());
}

7)To Submit Response to Survey List


function SubmitVote()
{
//Get the Group of radio Buttons for vote options  and get the selected value
//alert($("input[name='grpRadio']:checked").val());
if (undefined === $("input[name='grpRadio']:checked").val())
{
// do something
alert('Please select any response');
return;
}
// Get the current context
var context = new SP.ClientContext.get_current();
// Get the current site (SPWeb)
var web = context.get_web();
// Get the survey list
var list = web.get_lists().getByTitle('surveyListname');
 
var itemCreateInfo = new SP.ListItemCreationInformation();
var listItem = list.addItem(itemCreateInfo);
var response=document.getElementById('SelectedRadio').value;(response stored in hidden field)
var questionId=document.getElementById('CurrentQuestion').value (question's internal name stored in  hidden field)
/* Set fields in the item.
In managed code, this would be listItem[fieldname] = value.
In Javascript, call listItem.set_item(fieldName,value).
*/
listItem.set_item(questionId, response);
listItem.update();

 
// Create callback handlers
var success = Function.createDelegate(this, this.onSuccessVote);
var failure = Function.createDelegate(this, this.onFailureVote);
// Execute an async query
context.executeQueryAsync(success,failure);
}
// Async query succeeded.
function onSuccessVote(sender, args) {
alert('Thanks for responding Survey');
// Refresh the page.
// SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
}
// Async query failed.
function onFailureVote(sender, args) {
alert(args.get_message());
}


8)Add the above code lines  in txt file as follows

///less than sign![CDATA[   -- above code lines  here--

]]grater than  sign script ends

 //static html  here inside div div to assign generated html)
9)To debug above code place debugger; after any code line,which helps you to debug client object code with Visual Studio debugger.

10)Save this file as .txt file and upload to library and refer this link in content editor  webpart
This post is for good maintainability of code  on Sharepoint site itself .  That's gr8.. .  :)

Download Source Code

Wednesday, November 23, 2011

EnterPrise Content Types:Download Document Sets in Zip Format

What are the Document Sets?
 Its a Content type which  groups documents with a single work item and wrap them into a single version or workflow.
To add a new custom button to the Manage tab of the Document sets ribbon,
To export document sets so that they can be downloaded as a single ZIP file.

1) Create the Empty SharePoint Project.
 Add the reference of  C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.Office.DocumentManagement.dll
C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Web.dll

2) Create the Delegate Control with Site Scope Feature

i) Add the empty element in solution Right click ProjectAdd new Item Add empty element name as RibbonZipDelegateControl. And Delegate Control xml as shown in Image

ii) In Page load event write the logic to export Document Sets to zip file

iii) Add the Safe Control entry in web.config

SafeControl Assembly="DocsetRibbonDelegate, Version=1.0.0.0, Culture=neutral, PublicKeyToken=492efe3bf2c2f2b0" Namespace="DocsetRibbonDelegate" TypeName="DocsetRibbonDelegate"
3) Create Web Scoped Feature for the Custom Action Which Raise DownloadZipDelegateEvent Event (In Manage Tab Of Document Sets)

i) Add the empty element in solution Right click ProjectAdd new Item Add empty elementname it as RibbonDelegateCustomAction. And Delegate Control xml as shown in Image

ii) Create Image Mapped folder to display Icon of Image and Provide its Path in Custom Action
using System;
using Microsoft. SharePoint;
using Microsoft.Office.DocumentManagement.DocumentSets;
using System.Web.UI.WebControls;

namespace DocsetRibbonDeleagate

{

public class DocsetRibbonDelegate : WebControl

{

const string EVENT_NAME = "DownloadZipDelegateEvent";
const string MIME_TYPE = "application/zip";
protected override void OnLoad(EventArgs e)

{

this.EnsureChildControls();
base.OnLoad(e);
if (this.Page.Request["__EVENTTARGET"] == EVENT_NAME)

{

SPListItem currentItem = SPContext.Current.ListItem;

DocumentSet currentDocset = DocumentSet.GetDocumentSet(currentItem.Folder);

this.Page.Response.ContentType = MIME_TYPE;

currentDocset.Export(this.Page.Response.OutputStream, 1024);

this.Page.Response.End();

}

}

}

}

4) Create Web Scoped Feature for the Custom Action Which Raise DownloadZipDelegateEvent Event (In Manage Tab Of Document Sets)
i) Add the empty element in solution Right click ProjectAdd new Item Add empty elementname it as RibbonDelegateCustomAction. And Delegate Control xml as shown in Image

ii) Create Image Mapped folder to display Icon of Image and Provide its Path in Custom Action
 
5) Enable the Document Set Content Type
i) Site Settings Site Collection FeatureEnable Document Sets Feature
ii) In any Document Library Setting Advance SettingsEnable Management of Content types.
iii) Add from existing Content TypesSelect Document Set Content Type
iv) In Document Library, Create new Document Set and Deploy the solution as stated in step 1 and3 Go to Managed tab Export document Set in zip file

msdn References

Saturday, October 29, 2011

Sharepoint 2010 REST API to get the List and Library Data


1)What is REST?
Representational State Transer

2)What we can do with it?

i) Query Service Application  like excel services
 and display the excel Charts.
 ii)Query  List Data and Display data with Jquery or Silverlight(/_vti_bin/listdata.svc)

Wednesday, October 19, 2011

Sharepoint 2010 Social Features:Tag Cloud By AccountName


In OOB tag cloud, we get tag cloud only by Current user or By All tags.
To Customize tag cloud by accountname or profile ,
1. Add the reference of /_layouts/1033/styles/socialdata.css in page layouts or masterpage.

2. Add dll reference C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\microsoft.sharepoint.portal.dll
3. In Visual studio, Right click solutionAdd service reference click on ‘Advanced’ buttonAdd web referenceclick link Web services on local machine.
4. Search for socialdataservice.asmx.

public class TagWP : WebPart
{

localhost.SocialTermDetail[] details;

localhost.SocialDataService objSocialDataService = null;

long tagCount = 0;

protected override void CreateChildControls()

{

objSocialDataService = new localhost.SocialDataService();

int maximuItems=10;
int intstartIndex=1;
objSocialDataService.Credentials = System.Net.CredentialCache.DefaultCredentials;
string accountname= SPHttpUtility.HtmlEncode(Context.Request.QueryString["accountname"]);
details = objSocialDataService.GetTagTermsOfUser(accountname, maximuItems);
}
protected override void Render(System.Web.UI.HtmlTextWriter writer)

{
writer.Write("DIV id='tagCloudDatatagCloudByProfile' class='ms-TagCloud ms-TagCloudLink


");

writer.Write("DIV id='tagCloudByProfile'

");

Sunday, October 9, 2011

Sharepoint 2010 Social Features: Rating Publishing Pages/Blog pages

1)Enable the publishing features in site collection/site level

In Page Library Settings-->Rating Setting -->Enable the Contents to be rated.
Edit the Page in Sharepoint Designer or modify the Pagelayouts.

2)Add the namespace
%@ Register TagPrefix="SharePointPortalControls" Namespace="Microsoft.SharePoint.Portal.WebControls" Assembly="Microsoft.SharePoint.Portal, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %

3)Make sure that User Profile Service application is running in CA-->Manage Service applications
Add Rating Control  in Page Layout
SharePointPortalControls:AverageRatingFieldControl FieldName="Rating" runat="server"

Make sure that Field Name matches the Rating Column Name in Page Library.
4) To view the quick effects
CA > Monitoring > Timer Jobs > Review Job Definitions > look for 'User Profile Service Application - Social Data Maintenance Job' and 'User Profile Service Application - Social Rating Synchronization Job'.
Run the jobs.
5)If You get the Error 'Object reference not set to an instance' on viewing rated publishing Page
cmd-->inetmgr ->Restart SharePoint Web Services under Sites

6)
Include the reference of JS file in Page Layouts
script type='text/javascript'
$(document).ready(function() {
var pathname = window.location;
var soapEnv ="soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>\
soap:Body>\
GetRatingOnUrl xmlns='http://microsoft.com/webservices/SharePointPortalServer/SocialDataService'>\
url>+ pathname + /url>\
/GetRatingOnUrl>\
/soap:Body>\
/soap: Envelope>"
alert (soapEnv);
$.ajax({
url: "http://servername/_vti_bin/SocialDataService.asmx",
type: "POST",
dataType: "xml",
data: soapEnv,
complete: processResult,
contentType: "text/xml; charset=\"utf-8\""

});

});

function processResult(xData, status) {

var result = $(xData.responseXML).find("Rating")
//get rating value from webservice
var avg = parseFloat(result.text());

$(".ms-currentRating img").addClass(getClassNameForRating(avg));

}
function getClassNameForRating(rating) {
//apply class according  to ratings
if(isNaN(rating)

rating = 0)

return "";

if (rating < 0.25)

return "ms-rating_0";

if (rating <; 0.75)

return "ms-rating_0_5";

if (rating <; 1.25)

return "ms-rating_1";

if (rating < 1.75)

return "ms-rating_1_5";

if (rating < 2.25)

return "ms-rating_2";

if (rating < 2.75)

return "ms-rating_2_5";

if (rating < 3.25)

return "ms-rating_3";

if (rating < 3.75)

return "ms-rating_3_5";

if (rating < 4.25)

return "ms-rating_4";

if (rating <; 4.75)

return "ms-rating_4_5";

else

return "ms-rating_5";

}



/script>



Monday, September 19, 2011

OOB authorization with SPSecurityTrimmedControl

Using In Webparts
1)Declare SPSecurityTrimmedControl
SPSecurityTrimmedControl stcEditItem = new SPSecurityTrimmedControl();


2)Define Controls in WebPart
protected override void CreateChildControls()

{

stcEditItem.ID = "idPrm";

stcEditItem.Permissions = SPBasePermissions.ManageWeb;

ltrPopup.ID = "ltrPerm";

stcEditItem.Controls.Add(ltrPopup);

this.Controls.Add(stcEditItem);
}
3)Render the Trimmed Html contents,Now these content are available to administrators only


protected override void Render(HtmlTextWriter writer)

{

StringBuilder sb = AddModalPopUp(SPContext.Current.Web);

ltrPopup.Text = sb.ToString();

stcEditItem.RenderControl(writer);

}
Using in Visual Webpart
Open the .ascx file and add the controls inside SPSecurityTrimmedControl
SharePoint:SPSecurityTrimmedControl ID="ctrlSecurityTrimmed" runat="server" Permissions="ManageWeb">
controls. here..
SharePoint:SPSecurityTrimmedControl>

'value does not fall in expected range' When assigning SPUser to ListItem


If you try to assign,
ListItem["UserField"]=SPContext.Web.CurrentUser
And you get th Error  " value does not fall in expected range"
Cause:  ListItem is in different Sitecollection
So Directly You can not assign current user.
Resolution:
SPUser differntSiteCollectionUser = differentWeb.SiteUsers.GetByEmail(currentUserMailId);-->GetmailID with SPFieldUserValue

Thursday, September 8, 2011

Modal Popup and The Notification Area

Here I am covering
        1)Passing Url to Modal Popup from Server code in .cs file
          i)add the hiddenfield control to .aspx page          
and set value in cs file
hdnUrl.Value = "../Lists/ListName/NewForm.aspx?RootFolder=&";

        2)On Click of Ok button of Modal Popup Displaying the message in notification area which is part of sp2010 framework
Add following in Javascript tags
var url = document.getElementById('').value;

var options = {

url: url

title: "title",

allowMaximize: true,

showClose: true,

dialogReturnValueCallback: refreshCallback

};

function open() { SP.UI.ModalDialog.showModalDialog(options); }

function silentCallback(dialogResult, returnValue) {

}

function refreshCallback(dialogResult, returnValue) {

SP.UI.Notify.addNotification('Successful!');

SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);

}


Invoke the function

asp:Label runat="server" ID ="lblr" Text ="Open Popup">

Friday, September 2, 2011

To Position the Modal Popup Correctly...

Override the following css class and update the refering css file
.ms-dlgContent

{
position:fixed !important;
}
or use CSSRegistration.Register("_/layoout%Path%..") method (in CreatechildControl for Webpart/Prerender for usercontrol).

Tuesday, August 16, 2011

Check if current user is member of Sharepoint Group in Elevated Privileges Code Block

SPUserToken userToken = SPContext.Current.Web.CurrentUser.UserToken;

SPSecurity.RunWithElevatedPrivileges(delegate()

{

using (SPSite site = new SPSite(weburl, userToken))

{
using (SPWeb web = site.OpenWeb())

{

SPGroup group = web.SiteGroups[];


if (!web.IsCurrentUserMemberOfGroup(group.ID))

{

}

Friday, August 5, 2011

WebEventReceivers on Publishing Custom Site Template

To Get the Publishing custom site template
type in browser   http://server:port/sites/publishingsite/_layouts/savetmpl.aspx
and save the template.

Prerequisites for Restoring Publishing Custom Site Template without errors
 1)Error for activating feature with specific guid
    If  you restore the Publishing template on  any other non-publishing site collection ,you will get the error for activating feature with specific guid.
To avoid this ,restore this site template in publishing site collection only.

Still if you are getting the error,
Open the WSP Package in Visual Studio 2010
Search for Onet.xml in the solution.
Ctrl+F Find the featureId for which you are getting error.
Activate it in Parent site collection and You are done.

2)Web Page not found error when subsite is created using publishing custom site template.
Write the event Web Event Receiver to set the welcome Page

public class EventReceiver1 : SPWebEventReceiver

{

public override void WebProvisioned(SPWebEventProperties properties)

{
base.WebProvisioned(properties);

SPWeb web = properties.Web;
if (properties.Web.MasterUrl.Contains("MasterPageNameofcustomTemplate") )

{

web.AllowUnsafeUpdates = true;

SPFolder rootFolder = web.RootFolder;

rootFolder.WelcomePage = "sitepages/customwelcomePage.aspx";

rootFolder.Update();

web.AllowUnsafeUpdates = false;

}

}

If you know the better approach to attach event receiver to particular site template only please add the comment

Thursday, August 4, 2011

A Method To Get Selected Value in spuc:PeopleEditor control (Quickly)

-- Add Control in ascx


AllowEmpty="true" MultiSelect="false" SelectionSet="User" />
 
-- Get User value in ascx.cs
public SPUser GetUser(PeopleEditor p)

{

PickerEntity entPropMgr = (PickerEntity)p.ResolvedEntities[0];

SPFieldUserValue Proposalmgrvalue = new SPFieldUserValue(SPContext.Current.Web, Convert.ToInt16(entPropMgr.EntityData[PeopleEditorEntityDataKeys.UserId]), entPropMgr.Description);

if (Proposalmgrvalue != null)

return Proposalmgrvalue.User;

else

return SPContext.Current.Web.CurrentUser;



}

Wednesday, August 3, 2011

SPDispose Check Results

- I have noticed that objects(SPWeb) created inside for loops are not being disposed. These objects need to be disposed eventhough you main block of code is "Using".

- Also when you use following snippet it will not dispose SPSite object:
using(SPWeb oWeb=new SPSite("http://abc").openWeb())

{

-------

}
Here SPSite object is not disposed so follow below style in case of such scenerios:

using(SPSite oSite=new SPSite("url"))

{

using(SPWeb oWeb=oSite.OpenWeb())

{

------

}

}


This will solve the problem of disposing.
- Do not use "Using" when you work with SPContext. As SPContext are disposed automatically and if you use withing Using block than it will dispose SPWeb object and page will not work.

Thursday, July 21, 2011

Uploading WSP Package as Farm solution in CA with Powershell ISE

1)Open file
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\Config\PowerShell\Registration\SharePoint.ps1. In windows Powershell ISE
and Execute

2)In new file
Add-SPSolution “D:\Deploy\MySharePointSolution.wsp“


Install-SPSolution –Identity MySharePointSolution.wsp –WebApplication http://myspwebapp –GACDeployment
and  execute.

Check in Central Admin-->System Settings-->Manage Farm solution -->MySharePointSolution.wsp“ is deployed or not .
There is no UI way to upload and activate solution at farm level.









Tuesday, July 12, 2011

Comparing the old value and new value in Itemupdating Event

In Itemupdating event Of SPItemeventReceiver class

properties.ListItem["column name"]  gives the old value (b4 updating)
properties.AfterProperties["column_0x0200_name"]  gives the new value (after updating)

where column_0x0200_name is the internal name of column.

Saturday, July 9, 2011

Modal Popup with Content Editor Webpart

Open the sharepoint Site
In Ribbon,Find Insert Link-->Select Webparts-->In Media and Content Category-->Select Content Editor Webpart.-->Add/Edit the webpart

In SP 2010, Select Contents in CEWP, Format--> Html Source in the ribbon,
Add the javacript code
<script type="text/javascript">
     function OpenDialog(URL) {
         var NewPopUp = SP.UI.$create_DialogOptions();
         NewPopUp.url = URL;
         NewPopUp.width = 700;
         NewPopUp.height = 350;
         SP.UI.ModalDialog.showModalDialog(NewPopUp);
     }
 script>

"javascript:OpenDialog(‘../_layouts/MyAppPage/MyPage.aspx’)"--To Make it Server relative.
So that Dialog box opens anywhere in site collection

Monday, June 13, 2011

Debugging On Integration server

If you are not able to debug on Integration server
Do One thing,  Naviagate to
Central Admin Site -->Security -->configure Your service account here
reset IIS
when You attach to worker process you must me able to see w3p.exe on your user account.

Friday, June 10, 2011

Why the webpart dont get deployed even if added to solution?

In large Visual studio 2010 , if the webpart is note getting deployed to the site after successful build and deploy
try following
Check in the package designer , if your webpart name exists in package
if not then the feature designer and click on the Edit File Link,Add the webpart you are searching for.Package-->Build-->Deploy.

Thursday, June 2, 2011

How to Attach the EventReceiver to Particular List



1)Create  EventReceiver  ,Make sure that  Its  Feature  Scope  is Web Scoped,   Otherwise event will fire on all the Lists.

2)Make sure that ,Event receiver feature is deployed in the scope where List Exists.

3)In Element.xml , In receiver tag, modify the ListTemplateID to ListUrl="List/ListName"
Make sure that the path for ListUrl is correct, It is different for document libraries,Announcements and other list types
If its not correct then you will get Nativehr error


4)If still eventreceiver dont get  fired then Check SharePointProjectItem.spdata
In ProjectItem tag , check for Supported scope .It should be web only

4)Write the solutionValidator   to Validate above things before deploying the Event Receiver.

Thursday, May 26, 2011

Beauty Of Linq in Sharepoint

Linq Query to Get the ListItems for List in  One Step
Namespace:System.Linq, System.Collections.Generic    

IEnumerable results = lstMembershipList.Items.Cast().Where(item => item["EntityType"].ToString().Trim() == "Project" && item["Association"].ToString().Trim().ToUpper() == associationType

Monday, May 23, 2011

Search Architecture in Sharepoint 2010

While customizing the Search,Its very much important to understand the search Architecture

1)Create the metadata columns which gets values from Taxonomy term store
In background  Metadata property and Crawl properties are generated which requires crawl time
Now your task is to map  and index this properties for search.

2)Create the Search Scope

3)Use query object model  to query scope and to show  customize  metadata columns in grid

I will make this post more compehensive with Images and navigations . Happy Reading!!

Tuesday, May 17, 2011

Sharepoint 2010 Enhanced Event receivers

Following  event is called when site collection is created
public class EventReceiver1 :SPWebProvisioningProvider

{
public override void Provision(SPWebProvisioningProperties props)


{

throw new NotImplementedException();

}
 

}

Following event is called when subsite is created


public class EventReceiver2 : SPWebEventReceiver


{
public override void WebAdding(SPWebEventProperties properties)

{

base.WebAdding(properties);

}
}

Sunday, May 15, 2011

Understand the feelings of TFS which is integrated with Sharepoint Project in VS2010 :)

There are lot of enhancements tfs with visual studio 2010 over visual studio 2008.Lot of automatic things. But Some times we need to take care of.
For example,

1)When you move the files from rootfolder to mapped folder ,still the virtual instance of original file remains as it is for that you need to unload the project
Right Click-->unload the project  then again reload.

2)When you delete the Sharepoint Project Items, And you start packaging the solution ,compiler cries  'could not find the deleted file path'.

thus you need to edit the .feature file  and remove the guid projectitemreferance and package again.
you need to edit the .csproj file-->ctrl+f-->Find project referance guid as mentioned above.And remove the referance

If you know better way or best practices working with tfs integrated with sharepoint project please do the comments

Friday, April 15, 2011

Writing Code Behind for MenuItems defined in Custom Action

A)

When ever you want to  add the application page to Particular location in sharepoint site
Get the reference of this site
http://www.customware.net/repository/pages/viewpage.action?pageId=69173255
for example


To add code behind, You need to inherit  the class from MenuItemTemplate, and to Capture the Postback events inherit for Interface IPostBackEventHandler
public class MyListSiteActionMenu : MenuItemTemplate, IPostBackEventHandler
{
public MyListSiteActionMenu()
{
this.ID = "myOwnIdHura";
}

protected override void CreateChildControls()
{
this.Text = "Delete Item";
this.Description = "Deletes Item";
this.ClientDEFANGED_OnClickPostBackConfirmation = "Are you sure you want to delete this item?";
this.ClientDEFANGED_OnClickUsingPostBackEvent = this.ID;
}

public void RaisePostBackEvent(string eventArgument)
{
SPContext.Current.ListItem.Delete();
SPUtility.Redirect(SPContext.Current.List.DefaultViewUrl, SPRedirectFlags.Default, this.Context);
}
}

Some more links  adressing postbacks of  Menuitem template
http://www.dev4side.com/community/blog/2010/3/9/implement-postbacks-in-the-spmenufield-sharepoint's-control.aspx

B)Modifing the text of the MenuItem depending on  Custom List Property value
in 

Psedo Code as follows
CreateChildControl()
{
 //Code to display text of  menuitem depending on Custom List Property value
set the text of menuitem  according to property of list 


RaisePostBackEvent(string eventargument)
{
//updated list Propery on menuitem click
list.rootfolder.Addproperty();
list.rootfolder.SetProperty() ;






Tuesday, February 1, 2011

How to enable Powershell’s Integrated scripting environment for running Sharepoint 2010

Run following commands on powershell
Import-Module ServerManager; Add-WindowsFeature PowerShell-ISE
alternatively
Search for server manager and add this feature as follows


Configuring ISE for sharepoint
• Copy or type the following text in the Command Pane (View > Go to Command Pane) and press ENTER:


# Creates a local user PowerShell ISE profile

if (!(test-path $profile ))

{new-item -type file -path $profile -force}

# opens it for edit

psEdit $profile

• Running these commands will open a new script file in the Script Pane. Type the following commands in the script file and save it by clicking the Save button on the toolbar:

# Copy the following into the new file and save it

cd 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\CONFIG\POWERSHELL\Registration'

.\SharePoint.ps1

cd \

From now on, the SharePoint cmdlets will automatically load every time you start Windows PowerShell ISE as the same user. If you are still having problems using it, you may need to run it as an Administrator by right-clicking the shortcut and selecting Run as administrator (you can also force it to run as an administrator every time by right-clicking the shortcut, selecting Properties and then the Advanced button).

Tuesday, January 11, 2011

How to Create the Sharepoint 2010 Projects Where MOSS 2010 is not Installed?

Hello EveryOne,

        This article is just for knowledge sake and  to know about managing on machine where sharepoint 2010 is not installed.
If you have installed VS2010(visual studio ultimate) ,& Navigated as  Start ->VS2010 ->Run as administrator->New Project->Sharepoint 2010. You will get the popup that you can not create the sharepoint projects as MOSS 2010 is not installed.


But dont fear,If there is Will , there is Way :-)
Follow me as follows
1)Start -->Run-->RegEdit-->Select HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\14.0

and Export the file
and Import on  machine where SP2010 is not installed.
2)Now you wont get the popup but it will ask for the url in Wizard.
still go ahead. and put the IP address of the remote server or any dummy url.
and dont click on validate url  and click on finish

3)With this settings you can just  create the wsp but once you click on the Deploy the project
then again You have to face the same error that 'Sharepoint is not installed on local machine'

4)You can put your commands in a PowerShell script (.ps1) file and pass the path of the script file to PowerShell.exe.  Then you can just put this command in your post build event to run your PowerShell script after you compile

5)This will hold the command which will be executing on the remote machine where Sharepoint 2010 is installed.
to enable the remote execution of powershell commands follow the steps as given in this blog

6)If you get 'Access Denied error' while execution of PS commands, then check if Active directory domain services is enabled on Target machine


Thursday, January 6, 2011

How to Import CSV files to Term Store in Sharepoint 2010

1)Go to the term strore as directed in following Image


Click on view sample Import file  and Import it back.
This will generate the terms for tagging
Next I will demonstrate  how to use tagging..

2)Create the list with column of Type Managed Metadata as directed as following Image
3)When List is created and You add/update new items this column will have the ability to Select values from term store