Sep 29, 2009

How to access the Content Place Holder and Control placed inside some place holder in master page programmatically

There is requirement to access the control placed inside the PlaceHolderMain in the master page.

We can place this code inside the CreateChild Control method:

Control customControl = this.Page.Master.FindControl("ControlName");

Similarly to access the Content Place inside CreateChildControl method of webpart use this code snippet :

ContentPlaceHolder contentPlaceHolder = (ContentPlaceHolder)Page.Master.FindControl("ContentPlaceHolderName");

So now your job is done J

If you have any queries then please let me know

Enjoy!!!

Sep 25, 2009

Exploring “Location” object in javascript

Javascript location object is the property of the window property.

Properties

  • hash - The URL anchor part including the leading hash mark if one exists This is the part of the URL that is used to point to point to a particular part of a page where a named anchor is. The hash is the part containing the # sign that points to the particular page location.
  • host - The URL hostname and port. The URL http://spvm:1234/pages/default.aspx has the host value of http://spvm:1234. The colon and port is only included when specified. The URL http://spvm:1234/pages/default.aspx has the host value spvm:1234.
  • hostname - The URL hostname section
  • href - The entire URL. The following code will load the home default page:

location.href = "http spvm:1234.com/"

The following code will display the URL of the current page:

document.write(location.href)

  • pathname - The URL pathname section
  • port - The URL port section.
protocol - The URL protocol section including the colon after the protocol name. The values are normally http: or file
 
  • search - The URL query string section. This is the section after and including the question mark.
target - The URL link's target name.

Methods

  • reload() - The current window document is reloaded. If a value of true is passed to the reload function, the reload is forced to do an HTTP GET of the document. This is not normally done but is useful when you think the server contents may be different from your cache.
  • replace(URL) - Requires a URL as a parameter. It loads the document at the URL on top of the current document. A new entry is not placed in the history object.

Calling javascript from the XSLT on page load.

This is the first article in exploring the power of javascript when called from XSLT.

XSLT is basically used to render the xml in specified format.Here the requirement is to call some javascript function when xslt is rendering the xml.

In this article we are calling javascript on page load .

Scenario : On page load we want to fill some value in text box coming coming from the property defined in the xml .So first we need to access the property value inside javascript and then on page load need to fill the value inside the textbox.

Here is the sample javascript to be used inside the sample.xsl file

<xsl:template name="picture">

<script type="text/javascript">

function myFunction()

{

var url = ']]><xsl:value-of select="substring-before(@PictureUrl, ',')" />';

var txtBox = document.getElementById('textBox');

txtBox.value = url;

}

_spBodyOnLoadFunctionNames.push("myFunction");

]]>

script>

xsl:template>

Keep watching this space for more in javascript and XSLT.If you have done something then please share.

How to attach a process when activating or deactivating features from command prompt.

This is bit tricky one as often we have some feature receiver class with the feature and we want to debug it .

When we activate the feature through UI (ie from the site features) we attach the w3p process and debug the feature receiver code but this does not happen while doing the same from command prompt

So for this follow these steps :

1) Type the command to activate the feature in command prompt :

Stsadm –o activatefeature –name “feature name” –url

2) As soon u press enter , press Pause button from the keyboard.

There should not be any delay in these two actions as this is very fast process .

3) Now go to the solution in visual studio and attach the “stsadm” process from attach process tab

4) Now come to command prompt and press any key to resume the process.

Now you can debug the feature receiver code

So your job is done.

Enjoy!!!

How to get the Date Time from the regional settings of the page

To get the Date Time related information from the site’s Regional settings ,here is the sample code snippet.

SPSite site = new SPSite("http://spvm:1234/");

SPWeb web = site.OpenWeb();

DateTime dt = web.RegionalSettings.TimeZone.LocalTimeToUTC((DateTime.Now));

This way we can get the current time zone settings like which time zone we are using and date and time

So your job is done

Enjoy !!!

Sep 19, 2009

Add custom groups in the quicklaunch of the site

Objective is to add the custom created group in the quick launch of the site.I tried to explore the web and site object to get the handle of the people and group quick launch,but directoly it does not exposes anything..then i get this property to access the quicklaunch..

Here is the code sample..

site.AllProperties["vti_associategroups"] += ";" + oGroup.ID;
add custom group in the quicklaunch collection in the following way..

happy coding..

How to get the SP User ‘Owner” object of the site

Objective was create the custom group,and while creating custom group we need to specify the owner of the group,So we accessed the SPUser object of the owner in this way.This is the best way as there is no need of specifying any hard coded values.

SPUser owner =null;
owner = subSite.SiteGroups.GetByID(int.Parse(subSite.Properties["vti_associateownergroup"]));

Similarly Members group and visitor group can be accessed
SPUser member =null;
owner = subSite.SiteGroups.GetByID(int.Parse(subSite.Properties["vti_associatemembersgroup"]));

SPUser visitor =null;
owner = subSite.SiteGroups.GetByID(int.Parse(subSite.Properties["vti_associatevisitorgroup"]));

Apply custom master page on the application pages(Branding of Sharepoint Site)

Purpose : To apply custom master page on the application pages apart from the custom pages.
Normally in a sharepoint site ,we find that look and feel of the site is not consistent through out the site, there may be application pages which are different from the home page of the site.Now the problem is that since these are admin pages , so we cannot do much modification on these pages, and moreover if we go in sharepoint designer and changes the page from there than these changes will appear at farm level. So there is another way branding these admin pages is through HTTP Module, which will change the master page of a particular admin page at run time without effecting any thing on the page. This way we can have consistent look and feel through out the site.

Steps :
1) Open visual studio
2) Create a new project of type class library
3) Add sharepoint reference to it
4) Inherit the class from “IHttpModule” class

Follow this code:
namespace MyModule
{
public class LogoutModule : IHttpModule //inherit from the class
{
public void Init(HttpApplication app)
{
// Create a event handler to execute the process
app.PreRequestHandlerExecute += new EventHandler(app_PreRequestHandlerExecute);
}

void app_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current; // Get the current context of the pagee
Page page = context.CurrentHandler as Page;
if(page!=null)
{
page.PreInit +=new EventHandler(page_PreInit);
}
}
// Application master page can be changed only on the PreInit method of the page only
void page_PreInit(object sender, EventArgs e)
{
Page page = sender as Page;
if (page != null)
{
if (page.MasterPageFile.Contains("application.master"))
{
page.MasterPageFile = @"\_LAYOUTS\CustomApplicationMaster\Customapplication.master";
}
}
}
public void Dispose()
{
}
}
}

Your job is done..

Enjoy!!!

Redirect the page using HTTP module

Many times we need to redirect the page to some custom page based on some processing,this custom page can be some error page or any other page.So to achieve this we are using HttpModule and HttpHandler.

Steps :

Steps :
1) Open visual studio
2) Create a new project of type class library
3) Add sharepoint reference to it
4) Inherit the class from “IHttpModule” class

Follow this code:

---------------------------------------------
namespace MyModule
{
public class LogoutModule : IHttpModule //inherit from the class
{
public void Init(HttpApplication context)
{
// Create a event handler to execute the process
context.EndRequest += new EventHandler(context_EndRequest);
}

void context_EndRequest(object sender, EventArgs e)

{

Page page = HttpContext.Current.CurrentHandler as Page;

if (HttpContext.Current.Request.Url.Equals("http://spvm:1212/Pages/Default.aspx"))

{

HttpContext.Current.Response.Redirect("http://spvm:1212/sites/dms/Pages/Default.aspx");

}

}

}

}

----------------------------------------------------

To execute the HttpModule it should be registered in the Web.Config file of site and dll in the GAC.

This is the entry in the web.config file

Under <httpModules>tag Section

----------------------------------------------------

<add type="ClassName,AssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5" />

-------------------------

Your job is done..

Enjoy!!!

Embedding the .css file in the page through web part

Purpose is to add the css file in the page through webpart.

So in the Create child control method of the webpart , create the object of the css and then insert in the header control of the page.Once this is done we can attach the css to any control.

Follow this sample code for the same.

protected override void CreateChildControls()

{

try

{

base.CreateChildControls();

Microsoft.SharePoint.WebControls.CssLink cssLink = new Microsoft.SharePoint.WebControls.CssLink();

cssLink.DefaultUrl = "/_layouts/1033/styles/Tab.css";

this.Page.Header.Controls.Add(cssLink);

}

Place the css file at the specified folder location and then create the object for the css and then add this object of css file in the page.

Now you can use the css classes in the controls.

Enjoy!!!

To get the welcome page of the publishing site programmatically

Objective is to get the handle of the welcome of the site.

This will work for collaboration portal

PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(SPContext.Current.Web);

SPFile welcomePage = publishingWeb.DefaultPage;

bool isWelcomePage = false;

if (welcomePage != null)

{

string welcomeUrl = welcomePage.ServerRelativeUrl.ToString();

}

This way we get the welcome of the current publishing site.

Enjoy!!!

Customizing custom webpart menu

Any standard web part within SharePoint would have menu options like Minimize, Close, and Modify Shared Web Part. We can even add our own custom menu options over there. They are referred to as verbs .There are three types of web part menu verbs.

Client Side –Where we can specify JavaScript there

Server Side – Where we can attach event handler over here.

Both – We could have both JavaScript and event handler specified.

In this example we will add all three types of the verb

Create a web part project within Visual Studio.

Put the following code for web part,It would have a lable that would show the text set using the event handler specified in the server side verb.

Code snippet:

public class CustomWebPartMenuVerbWebPart : System.Web.UI.WebControls.WebParts.WebPart

{

public CustomWebPartMenuVerbWebPart()

{

}

protected lblValue;

protected override void CreateChildControls()

{

lblValue = new Label();

this.Controls.Add(lblValue);

}

public override WebPartVerbCollection Verbs

{

get

{

// Client side verb

WebPartVerb clientSideVerb = new WebPartVerb(“clientID”, “javascript:alert(’Custom message from Java Script Verb!’);”);

clientSideVerb.Text = “Client Side Verb”;

// Server side verb

WebPartVerb serverSideVerb = new WebPartVerb(“serverID”, new WebPartEventHandler(ServerVerbEventHandler));

serverSideVerb.Text = “Server Side Verb”;

// Verb for both client side and server side

WebPartVerb bothSideVerb = new WebPartVerb(“bothID”, new WebPartEventHandler(ServerVerbEventHandler), “javascript:alert(’Custom message from Java Script Verb!’);”);

bothSideVerb.Text = “Both Side Verb”;

WebPartVerbCollection wbVerbCollection = new WebPartVerbCollection(base.Verbs, new WebPartVerb[] { clientSideVerb, serverSideVerb, bothSideVerb });

return wbVerbCollection;

}

}

protected void ServerVerbEventHandler(object sender, WebPartEventArgs args)

{

lblValue.Text=“message from Server Side Verb”;

}

}

Enjoy!!!

Injecting java script in sharepoint page programmatically using Http Module

Objective here is to create a Modal Disclaimer when user tries to edit his details in his MySite.


For this on the detials page a modal disclaimer will appear before users start editing/modifying their profile information they must acknowledge a “disclaimer” telling them about the ramifications of what it is they are doing. This disclaimer should be a modal dialog, i.e. they must read it and click it away.

Constraint :

Cannot touch the OOB EditProfile Page i.e cannot write any java script in the OOB page.

Solution : We have to embed javascript in the editprofile page..each time when the page loads and it should be displayed when the page loads and then modal pop window should come on top of the page…

For this we wrote one HTTP module which checks the URL of the current requested page and then takes the reference of Content Place holder main and then add javascript inside that place holder as control..

Since this modal pop window should fire when the loading of the page completes i.e javascript should fire with some differ..so for this we used ScriptLink link control :

Code for HTTP module

public void Init(HttpApplication context)

{

context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);

}

void context_PreRequestHandlerExecute(object sender, EventArgs e)

{

HttpContext currentContext = HttpContext.Current;

Page page = currentContext.CurrentHandler as Page;

if (page != null)

{

page.LoadComplete += new EventHandler(page_LoadComplete);

}

}

Code snippet for adding the control to the page

void page_LoadComplete(object sender, EventArgs e)

{

Page page = sender as Page;

if (page != null)

{

//Checking if the current requested page is the EditProfile page of the My Site then only proceed.

if (HttpContext.Current.Request.Url.AbsolutePath.ToString().Trim().ToUpper(System.Globalization.CultureInfo.InvariantCulture).Contains("/_LAYOUTS/EDITPROFILE.ASPX"))

{

//Get the PlaceHolderMain content place holder from the application master page

//to add the Script link control in the page

Control c = page.FindControl<ContentPlaceHolder>("PlaceHolderMain");

if (c != null)

{

ScriptLink link = new ScriptLink();

link.Defer = true;

link.Localizable = false;

//This is the .js file to open the ModalDialog box when user goes to EditProfile page

//this is the java script file which contains the code for the modal pop window

link.Name = "MyFolder/MySiteModalWindow.js";

c.Controls.Add(link);

}

else

{

//Since control object is null so don't insert ScriptLink control in the page

}

}

}

else

{

//Do not inject any script in the page

}

}

This way we can embed java script in to the page through Http module without touching the OOB page.

Enjoy!!!

Creating Search scopes programmatically

Requirement:Creating the scopes programmatically and creating the rule for it

We can create search scopes in two ways ,one is through providing the content source as scope rule and another is by providing the web address and then providing the url of the folder as the rule.

Through second way we can provide any list or document libraryy as the content source for the scope

We will go through each of them in detail .

Before creating scope check if scope already exists or not

To Check if scope already exists

Create one console application

and in it add Microsoft.Sharepoint.dll and Microsoft.Sharepoint.Office.Server.dll as reference and paste this code snippet in the main method

foreach (Microsoft.Office.Server.Search.Administration.Scope sspScope in

sspScopes)

{

if (sspScope.Name == ''ScopeName")

{

isValidScope = true;

break;

}

}

Create Using content source

//Add these references in the code

using Microsoft.Office.Server.Search.Administration;
using Microsoft.SharePoint;

SearchContext context;
using (SPSite site = new SPSite(”http://<SSPsite>”))
{
context = SearchContext.GetContext(site);
}
Schema sspSchema = new Schema(context);
ManagedPropertyCollection properties = sspSchema.AllManagedProperties;
Scopes scopes = new Scopes(context);
ScopeCollection sspScopes = scopes.AllScopes;
Scope newScope = sspScopes.Create(”Name”, “Description”,
null, // System.Uri object representing the owning site URL
true, // True to display the scope in the SSP Administrator UI
null, // A string specifying the alternate results page for the scope
ScopeCompilationType.AlwaysCompile); // Includes your content sources to the created Scope
foreach (string ContentSourceName in YourContentSourcesNames)
{
newScope.Rules.CreatePropertyQueryRule(ScopeRuleFilterBehavior.Include,
properties["ContentSource"], // Managed Property
ContentSourceName);
}
// Update Scopes
scopes.StartCompilation();

2)using scope rule as WebAdress and specify the url of folder

as scope.In this Scope is limited to a particular list.

This way we can include as many urls in the the scope rule

//Create the new scope

Scope newScope = sspScopes.Create(“Scope Title”, Scope Description, null, true, null, ScopeCompilationType.AlwaysCompile);

SPList ListName = site.RootWeb.Lists.GetByName("ListName");

if (ListName!= null)

{

//Scope Url is the PodCast List url.

string scopeUrl = ListName.ParentWeb.Url.ToString() + "/" + ListName.RootFolder.Url.ToString();

newScope.Rules.CreateUrlRule(ScopeRuleFilterBehavior.Include, UrlScopeRuleType.Folder, scopeUrl);

scopes.StartCompilation();

}

Thus scope is ready to use.

If you feel this content is of some use then please post your comments.

Enjoy coding!!!

Using linq query to get the data from the list or any collection

LINQ that allows to query SharePoint lists or any collection using familiar LINQ syntax. LINQ stands for Language Integrated Query and is one of the core features of Microsoft's .NET Framework 3.5 release.

In this example we are querying the web feature collection by using this query

SPFeatureCollection webFeatureColl = web.Features;

var webActivatedFeatureresults = from SPFeature feature in webFeatureColl

where feature.Definition.DisplayName == featureToActivate

select feature;

List<SPFeature> webActivatedFeature = webActivatedFeatureresults.ToList<SPFeature>();

Same way we can query the list collection.this is faster than query the list collection using the CAML query.

More on Linq will be next post.If you have any important stuff to share regarding the same,then keep posting

Enjoy coding !!!

Code to create site using a template (Document workspace)

This is sample code for creating the site programmatically using site template stored in the site template gallery.


If we are creating site through the console application ,then replace the SPContext with the site or web object


Code snippet


Guid siteID = SPContext.Current.Site.ID;


Guid webID = SPContext.Current.Web.ID;


SPSecurity.RunWithElevatedPrivileges(delegate()


{


using (SPSite site = new SPSite(siteID))


{


//Get the template from the site template gallery


SPWebTemplate oWebTemplate = site.GetCustomWebTemplates(Convert.ToUInt32(1033))["XXXX"];


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


{


//Create site without copying the users from the top site


web.AllowUnsafeUpdates = true;


string webUrl = "Site Name";


subSite = web.Webs.Add(webUrl, "SiteName", Site Description", 1033, oWebTemplate, false, false);


}


}


});


Note: If we want to create a site based on the OOB available templates ,just modify the code accordingly


subSite = web.Webs.Add(webUrl, "SiteName", Site Description", 1033, "TemplateName", false, false);


Lets look at the parameters passed in it


strWebUrl:


A string that contains the new Web site URL relative to the root Web site in the site collection. For example, to create a Web site at http://MyServer/sites/MySiteCollection/MyNewWebsite, specify MyNewWebsite


strTitle


A string that contains the title.


strDescription


A string that contains the description.


nLCID


An unsigned 32-bit integer that specifies the locale ID. You can find a complete list of local ID at the following URL:


http://www.microsoft.com/globaldev/reference/lcid-all.mspx


We have used “1033” for English – United States.


strWebTemplate


A string that contains the name of the site definition configuration or site template. The following table shows the values for the default site definition configurations that are included in an installation of Windows SharePoint Services


Value


Site Definition


STS#0 Team Site


STS#1 Blank Site


STS#2 Document Workspace


MPS#0 Basic Meeting Workspace


MPS#1 Blank Meeting Workspace


MPS#2 Decision Meeting Workspace


MPS#3 Social Meeting Workspace


MPS#4 Multipage Meeting Workspace


WIKI#0 Wiki


BLOG#0 Blog


useUniquePermissions


true to create a subsite that does not inherit permissions from another site; otherwise, false.


bConvertIfThere


true to convert an existing folder of the same name to a SharePoint site. false to throw an exception that indicates that a URL path with the specified site name already exists.


Enjoy coding !!!

Programmatically Adding List viewer Web part(for document Library) on the page

Objective is to add the listviewer web part on the page programmatically. I have a document library for which i want to add the list viewer web part on any page.

Create a console application and paste the code

Code snippet

class Program

{

static void Main(string[] args)

{

SPSite site = new SPSite("Site Url");

SPWeb oSubWeb = site.OpenWeb();

oSubWeb.AllowUnsafeUpdates = true;

//Get the object of the page as SPFile on which we need to add the listviewer webpart

SPFile oFile = oSubWeb.GetFile("default.aspx");

//Create the object SPLimitedWebPart Manager

SPLimitedWebPartManager oWebPM = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared);

//Get the object of the list of which we are creatin the list viewer webpart

SPList oSubSiteList = oSubWeb.Lists["Shared Documents"];

//Create the object of ListViewer webpart

ListViewWebPart oListViewWP = new ListViewWebPart();

//Set the properties of the webpart

oListViewWP.ChromeType = PartChromeType.TitleOnly;

oListViewWP.Title = "Shared Documents";

oListViewWP.ListName = oSubSiteList.ID.ToString("B").ToUpper();

//Define the zone in which webparts need to be added

oWebPM.AddWebPart(oListViewWP, "Zone 1", 1);

}

}

Your job is done....

Enjoy!!!

If you find this post useful then please post your comments

Programmatically create a generic list

Here we are creating a list programmatically in the sharepointe site and setting some of the default properties.

Here is sample code:

SPSite site = new SPSite("Site Url");

SPWeb oSubWeb = site.OpenWeb();

oSubWeb.AllowUnsafeUpdates = true;

//Here we are getting the list template type.If we want to create list of some other type,select some other template type.

SPListTemplateType templateType = SPListTemplateType.GenericList;

Guid listId = oSubWeb.Lists.Add("Sample List", "This is a sample List", templateType);

//Creating custom fields(coloumn) in the list

documentLibrary.Fields.Add("coloumn1", SPFieldType.Text, false);

documentLibrary.Fields.Add("coloumn2", SPFieldType.Number, false);

SPList list = oSubWeb.Lists[listId];

list.EnableVersioning = true;

list.OnQuickLaunch = true;

list.Update();

This way we can create a document library programmatically having custom columns for which quicklaunch ,Versioning enabled.

Enjoy!!!

Programmatically adding an item in the list

In the previous post i have explained how to create a list programmatically, here i am adding an item in the list.

Sample code:

SPListItemCollection oListItemColl = SPContext.Current.Web.Lists[“”].Items;

oWeb.AllowUnsafeUpdates = true;

SPListItem oItem = oListItemColl.Add();

oItem["Column1"] ="Test Value ";

oItem["Column1"] = "Test Value 2";

oItem.Update();

oWeb.AllowUnsafeUpdates = false;

Enjoy !!!

Creating Custom view of a list programmatically

Objective here is to create a custom view of the list and then setting this custom view of the list as a default view.

Here is the sample code:


SPSite site = new SPSite("http://spvm:2409");

SPWeb oSubWeb = site.OpenWeb();

oSubWeb.AllowUnsafeUpdates = true;

//SPListTemplateType templateType = SPListTemplateType.GenericList;

//Guid listId = oSubWeb.Lists.Add("Sample2 list Library", "This is a sample Document Library", templateType);

SPList list = oSubWeb.Lists["Sample2 list Library"];

SPSite site = new SPSite("Site URL");

SPWeb oSubWeb = site.OpenWeb();

oSubWeb.AllowUnsafeUpdates = true;

SPList list = oSubWeb.Lists["Sample2 list Library"];

//Create a custom view and then set the custom view as the default view of the list

SPView oView = list.DefaultView;

oView.Title = "CustomView";

//Add the available columns in the view

oView.ViewFields.Add("column2");

oView.ViewFields.Add("column1");

oView.Update();

list.Views["CustomView"].DefaultView = true;

list.Update();

Thus this way we can create our custom views.


Enjoy!!!


If you find this post useful then do post your comments....

How to get all the web of which the current logged in user is part of(Added in any of the Groups)

Scenario :We have a collection of web in the site collection,We need to get the collection of all the webs of which the current logged in user is part of ( present in any of the group)

Sample Code:

SPWeb oWeb = SPContext.Current.Web;

SPWebCollection oWebColl = oWeb.GetSubwebsForCurrentUser();

//This gives all the web object for which the current logged in user is

part of.

Enjoy !!!

Creating a long running operation page

This is very good feature to show the long running operations page while creating certain background operation like custom site creation wizard.

Code for this:

SPLongOperation operation = new SPLongOperation(this) {
LeadingHTML = "This is the description of my operation",


};

operation.Begin();
Thread.Sleep(2000);
operation.End("/Custompage.aspx");

Note: Put your code inside Operation.Begin() and Operation.End()

For more information visit

Microsoft.SharePoint.SPLongOperation

Enjoy!!!

Creating Custom Role Definition programmatically

Sharepoint provides many permission level like Full control ,Contributor,visitor etc...but there are scenario where we need to create our own role definitions which may be the combination of permissions available in two different OOB role definitions..

So through this we can create our custom permissions :

------------------------------------------------------------------------

SPWeb web= SPContext.Current.Web;

SPRoleDefinition role = new SPRoleDefinition();
role.Name = "Custom Role";

role.Description = "Custom permission level to View,Edit,Add list items";

role.BasePermissions = SPBasePermissions.OpenItems

| SPBasePermissions.ViewVersions

| SPBasePermissions.ViewFormPages

| SPBasePermissions.Open

| SPBasePermissions.ViewPages

| SPBasePermissions.UseClientIntegration

| SPBasePermissions.UseRemoteAPIs

| SPBasePermissions.CreateAlerts

| SPBasePermissions.ViewListItems

| SPBasePermissions.ViewPages

| SPBasePermissions.EditListItems

| SPBasePermissions.AddListItems

| SPBasePermissions.DeleteListItems;

web.AllowUnsafeUpdates = true;

web.RoleDefinitions.Add(role);

------------------------------------------------------

Once this is done ..this permission will be available when we create some group or add some user to the site...

Enjoy!!!

Creating custom groups and permissions associated with the groups

Here i m going to create the custom groups,custom permission level and association or binding between the group and permission level.

So first we are going to create the custom group

---------------------------------------
SPSite site = new SPSite("http://spvm:2409");

SPWeb oSubWeb = site.OpenWeb();

oSubWeb.AllowUnsafeUpdates = true;


oSubWeb.AllowUnsafeUpdates = true;

//Here get the owner group from the site...to get the other groups like member or visitor group follow the earlier post Click here.

SPGroup owner = oSubWeb.SiteGroups.GetByID(int.Parse(oSubWeb.Properties["vti_associateownergroup"]));

oSubWeb.SiteGroups.Add("Customgroups", owner, null, "Custom groups");

oSubWeb.Update();


---------------------------------------------------------------

Once the group is created we will create the custom permission level..

---------------------------------------------------------------
SPRoleDefinition role = new SPRoleDefinition();

role.Name = "CustomPermission";

role.Description = "Custom permission level to View,Edit,Add list items";

role.BasePermissions = SPBasePermissions.OpenItems

| SPBasePermissions.ViewVersions

| SPBasePermissions.ViewFormPages

| SPBasePermissions.Open

| SPBasePermissions.ViewPages

| SPBasePermissions.UseClientIntegration

| SPBasePermissions.UseRemoteAPIs

| SPBasePermissions.CreateAlerts

| SPBasePermissions.ViewListItems

| SPBasePermissions.ViewPages

| SPBasePermissions.EditListItems

| SPBasePermissions.AddListItems

| SPBasePermissions.DeleteListItems;

oSubWeb.AllowUnsafeUpdates = true;

oSubWeb.RoleDefinitions.Add(role);

---------------------------------------------------------------

Once the custom permission level is create ,now its time to bind this permission level to custom created group

----------------------------------------------------------------
//Name of the custom group created above

SPGroup oGroup = oSubWeb.SiteGroups["Customgroups"];

oSubWeb.AllowUnsafeUpdates = true;

SPRoleAssignment roleAssignment = new SPRoleAssignment(oGroup);

//Name of the role definition created above roleAssignment.RoleDefinitionBindings.Add(oSubWeb.RoleDefinitions["CustomPermission"]);

oSubWeb.AllowUnsafeUpdates = true;

oSubWeb.RoleAssignments.Add(roleAssignment);

oSubWeb.AllowUnsafeUpdates = true;</div>
oSubWeb.Update();

oSubWeb.AllowUnsafeUpdates = false;

---------------------------------------------------------------------

So your custom group with custom permission level is ready to use..

Enjoy!!!

How to programmatically get the Profile of the user from the MySite profile page

When we visit the MySite,there are two types of pages ,one is default page of the current user and other is the person.aspx which points to the profile of the user .This person.aspx can be of current logged in user or can be of any visited user.
So to get the profile of the user (current logged or visited user) programmatically ,we use "ProfilePropertyLoader sharepoint object .This works only on profile of the user and not on the home page.

This is the code below to load the profile
-------------------------------------------

ProfilePropertyLoader loader = ProfilePropertyLoader.FindLoader(this.Page);

if (loader != null)

{

Microsoft.Office.Server.UserProfiles.UserProfile profile = loader.ProfileLoaded;

if (profile != null)

{

String AccName = Convert.ToString(profile["AccountName"].Value, CultureInfo.InvariantCulture);

}

}

-----------------------------------------

Thus u can get the all the properties from the profile loader

Enjoy!!!

How to remove the value from the OOB choice type field in the column in list

Here the requirement is to add/remove value from the choice type field from the column created in list programmatically.

Here is the sample code for this..

-------------------------------------------------------------------

SPFieldChoice fieldName = (SPFieldChoice)ListName.Fields["ColumnName"];

//Check if the required choice value exist in the field

//If it exists then remove it from the choice collection

if (fieldName.Choices.Contains("ChoiceValue") == true)

{

fieldName.Choices.Remove(ChoiceValue);

fieldName.Update();

}

else

{

// Do nothing.Choice value does not exist

}

-------------------------------------------------

This way we can access any type of the column type provided by Sharepoint and add or remove the values programmatically

Your Job is done!!!

Enjoy!!!

Accessing SPUser from SPFiledUser

Here requirement is to get the SPUser object from the SPFieldUser. Sharepoint stores the “People and Group” column value in following format id;#domain\user (eg. 1;#SPVM\user) .So we need to get the SPUser object from the SPFieldUser .Once the SPUser object is retrieved ,we can access all the properties of the SPUser like Email,LoginName etc.

Similary we can access any column created using “People and Group” column type

Here is the sample code .Here I am taking the 1st object from the task List.

-----------------------------------------------------------

SPSite site = new SPSite("http://spvm:2409");

SPWeb oSubWeb = site.OpenWeb();

string assignedTo = string.Empty;

//Get the first item from the “Task” List

SPListItem oItem = oSubWeb.Lists["Tasks"].Items[0];

if (oItem["Assigned To"] != null)

{

assignedTo = oItem["Assigned To"].ToString();

SPFieldUserValue spfl = new SPFieldUserValue(oSubWeb, assignedTo);

SPUser oUser = spfl.User;

if (oUser != null)

{

assignedTo = oUser.Email;

//userName = oUser.Name;

}

}

----------------------------------------------------------

So your job is done.

Enjoy!!!

How to Customize the invitation message while adding the users to the group using Javascript

Objective is to customize the invitation message while adding user to sharepoint site.Though custmozing sharepoint pages are not recommended by Microsoft,but this is one way of customizing.

Open the AclInv.aspx page from the /layouts folder.

Add this script in the page...

<script>

function CustomMessage()

{

var txtBox = document.getElementById('ctl00_PlaceHolderMain_ifsSendEmail_txtEmailBody');

alert(txtBox);

txtBox.innerHTML = "Saurabh";

txtBox.readOnly = true;

}

_spBodyOnLoadFunctionNames.push("CustomMessage");

</script>



//

_spBodyOnLoadFunctionNames.push("CustomMessage");

This is the function called on load of the sharepoint page.



If there is some other way..then please keep posted

Happy Coding!!!

Hide the template from the site templates ( on create site page) through java script.

Recently i have interesting requirement,in which i have to hide the specific site templates while creating a subsite.
Now the problem was the required template was available under the custom template section ,so on page load first template section comes as default selected,so i have to select the appropriate template to check the available templates.

I tried to hide the template through object model ,but through object model I can remove the template permanently from the site,but here i have to hide the template.
So I tried this objective using javascript on the /_layouts/create.aspx page,which is not although not recommended to modify the OOB pages,To insert the javascript in to the page through HTTPmodule without touching the OOB page follow this post Link ,
but again challenge was this "Input Template Picker" control is a user control and on page loads it displays the template in the first tab only,so i checked the page view of the page and it contains only the value in the values in the first tab,
on clicking the next tab,control fires event through javascript and populates the control,so I was not able to capture the event.
Then while surfing I came across one blog which mentions about capturing the event when there is any change in page object,Bingo...now when i selects another tab , I was able to capture the event and write my logic to hide the template.
Here the javascript code contains an "onDocumentChange" DOM function which gets called when something changes on the page,Inside there is another delegate function which contains the logic is to get the collection of all the available option tag and then make the outerHTML value to empty.

javascript

Note: Here is another catch,first i tried to make the optionTag[i].Text to empty but what happened in the template selection panel,value disappeared but it still occupies the space and highlights on selection,so I make the outerHTML of the optionTag to empty.

So your job is done!!!
If you have any other method to do the same throug object model or through javascript then do reply

Enjoy!!!

How to get the Query string value through javascript

Requirement is to get the querystring value through javascript.


Here Querystring variable name is “Tag”


Add this function in the javascript block of the page and call according to the requirement.I am calling this function on page load.


Here is code:


-----------------------------



function querySt() {

var url = window.location.search.substring(1);

var qSColl = url.split("&");

for (i=0;i<qSColl.length;i++) {

qsValue = qSColl[i].split("=");

if (qsValue[0] == 'Tag') {

var tabValue = qsValue[1];

}

}

}

---------------------------------

So this way you can access any variable value from the querystring

So your job is done

Enjoy!!!

Limiting length of Multiline textbox(inside webpart) through javascript

Here the requirement is to limit the maxlength of multiline text box in webpart .This seems to be very simple problem,just set the property of MaxLength property of TextBox to some no,but when somehow this property does not work with Multiline Text Box..may be there will be some fix in future release.

So we fix this problem using java script

Add this javascript in the CreateChildControl method.

Here is javascript for this :

----------------------------------------------------------

StringBuilder javascript = new StringBuilder();

javascript.AppendLine("<script type='text/javascript'>");

javascript.AppendLine("function Validation(evt,maxLength)");

javascript.AppendLine("{");

javascript.AppendLine("if(evt.value.length > maxLength)");

javascript.AppendLine("{");

javascript.AppendLine("alert('Maximum 255 characters allowed');");

javascript.AppendLine("evt.value = evt.value.substring(0,maxLength);");

javascript.AppendLine("}");

javascript.AppendLine("}");

javascript.AppendLine("</script>");

if (javascript != null)

{

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "javascriptcode", javascript.ToString());

}

-------------------------------------------------------------

In above code we have written the java script and registered the client script in the page.Now we need to add this javascript event in the multiline textbox

-------------------------------------------------------------txtMultilineTextBox.Attributes.Add("onKeyDown", "Validation(this, 255)");

----------------------------------------------------------------
Now we have added the event in the text box for "onKeyDown" event .So whenever user exceed 255 characters in the text box this event will fire and limit the length.

Activating a feature in the subsite programmatically

Scenario :Acvtivating a feature programmatically in the subsite.Feature is activated at site collection with scope as (Web) level .

Implementation

: Find all the activated feature at site collection level with scope as web..match the feature id of the feature to be activated and add its id in the feature collection of the site

Sample Code:

string nameFeature = string.Empty;

foreach (SPFeature featureName in web.Features)

{

Guid guid = new Guid("F1EB325C-D3E9-4a2e-9B13-626AF5A1F601");

if (featureName.Definition.Id == guid)

{

subSite.AllowUnsafeUpdates = true;

subSite.Features.Add(featureName.Definition.Id);

subSite.AllowUnsafeUpdates = false;

break;

}

}

This way we can add this feature in the web.

Enjoy!!!

Feature Activation Dependency Concept

This is something that one feature is dependent on the activation of another feature before it gets activated. A good example is TeamCollab feature which activates so many other features .

So this will activate other features first and then activates the actual feaure.

<Feature

Id={GUID}

Title={title}

Description={Description}

Version={version}

Hidden={value}

Scope={value}

xmlns={namespace} />

<ActivationDependencies>

<ActivationDependency FeatureID = {dependent Feature GUID}/>

</ActivationDependencies>

Your Job is done..

Cheers!!!

Installing webpart as a feature

Another article in the series of exploring the power of features,In this article we installing webpart as feature.

Steps for creating the feature has already been explained in the previous post.Here is

Feature.xml

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

<Feature Id=" 8425EAF7-6ACE-4597-83C7-831CA8614D6D" Title="MySampleWebPart"

Description="Here is my sample web part"

ImageUrl="GenericFeature.gif"

Scope="Site" xmlns="http://schemas.microsoft.com/sharepoint/"> <ElementManifests>

<ElementManifest Location="elements.xml" />

</ElementManifests>

</Feature>

Element.xml

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

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

<Module

Name="WebPartPopulation"

List="113"

Url="_catalogs/wp"

RootWebOnly="TRUE">

<File Url="MySampleWebPart.dwp" Type="GhostableInLibrary" />

</Module>

</Elements>

Note: Here in the Url ,we have to give the path of the dwp file of the webpart ,so along with feature.xml and element.xml put the dwp file of the webpart also in the features folder and copy this folder in the 12 hive .

RootWebOnly attribute is true here means this webpart will be available only at the root level not at the subsite level.This can be changed to sub web level also.

Then install and activate the feature.

Make safe control entry in the web.config file

This feature will be available in the webpart gallery,we have to populate this feature before using

Enjoy!!!

To add event handler as a feature

Steps required to install master page as a feature.

There are two important files while creating the feature.
1) Feature.xml and Element.xml
Feature.xml tells the attributes like FeatureId,title ,scope and the location of the element file
Element.xml is the actual file that tells what this feature is actually doing.

2) Open Visual studio
3) Open a new project and select Class library type project
4) Right Click on the project name and new xml file and name it as feature.xml
5) Create a folder with name MasterPages which contains the master page

Feature.xml

<Feature Id=”95F25D4A-D256-4158-96FE-010F599149CC”

xmlns=http://schemas.microsoft.com/sharepoint/

Title=”Demo Master Page”

Scope=”Site” Version=”1.0.0.0″ Hidden=”FALSE” Description=”This Feature contains the demo master page”>

<ElementManifests>

<ElementManifest Location=”elements.xml” />

<ElementFile Location=”MasterPages\demomasterpage.master” />

</ElementManifests>

</Feature>

Now see the attributes required to create this featue.xml
Id :This is the unique id for each feature. This can be created
Goto Tools tab in the visual studio and select Create GUID and create a new GUiD
Title :To specify the name for the feature .Name of the Feature title and the name of the containing folder should be same
Description : To specify the description of the feature
Scope : This is very important property as this property defines the scope of the feature.
There are 4 types of scope :
a) Farm b) WebApplication c) Site d) Web
If scope is site then feature is installed at site collection level and it will be available to the root site and subsites below it.
If scope is web then the scope of the feature is web..

Hidden : This property specifies if this feature should be visible in the feature collection.This is important if user wants to activate the feature from the command line utility (i.e. stsad.exe)

Feature.xml specify the feature attributes but the
Now next element is the ElementManifests.
This contains two tags

This tells the location of the element file which contains the actual implementation of the feature

This tells the location of any other files that is required during the feature installation.In this scenario this the location of master page which is going to deployed
Here MasterPages is the name of the folder where it is stored(same as feature folder)
Element.xml

<Elements xmlns=”http://schemas.microsoft.com/sharepoint/”>

<Module Name=”DemoMasterPage” Url=”_catalogs/masterpage” Path=”MasterPages” RootWebOnly=”FALSE”>

<File Url=”demomasterpage.master” Type=”GhostableInLibrary” />

</Module>

</Elements>

This file tells us what exactly has to be implemented
Inside the tag <Module set some attributes like
Name : , Url : this tells the location where master page has to be installed, Path: This gives the relative path of the master page file ,RootWebOnly : This property tells if this action has to be performed at only root web or it should be available to all the subsites.

<File tag gives information about the master page and it should be installed on the server
this tells SharePoint the name of the file it is going to put at the master page gallery. The type is “GhostableInLibrary” - this means the file is still going to be on the 12 hive and SharePoint is going to keep a Ghosted reference to the file. Please refer to article 3

http://sharepointmagazine.net/technical/customisation/developing-a-custom-master-page-master-pages-and-sharepoint-part-3-of-6 for more information about Ghosting. To install and activate the columns

Note : Copy the features folder in the 12/Template/Features folder in the file structure and then install and activate the feature

Through command line utility
Go to run and write cmd to open the command prompt
Go to the 12 hive folder
Command :
To install feature
Stsadm –o installfeature –name “” [-force]
To Activate feature
Stsadm –o activatefeature –name “” –url “” [-force]
Now the feature is installed and activated at a particular site collection. Go to the site settings and click on master pages there the newly installed master page will be available in the master page drop down.

Your Job is done !!!
Enjoy!!!

Deploy Master page as feature

Steps required to install master page as a feature.

There are two important files while creating the feature.
1) Feature.xml and Element.xml
Feature.xml tells the attributes like FeatureId,title ,scope and the location of the element file
Element.xml is the actual file that tells what this feature is actually doing.

2) Open Visual studio
3) Open a new project and select Class library type project
4) Right Click on the project name and new xml file and name it as feature.xml
5) Create a folder with name MasterPages which contains the master page

Feature.xml

<Feature Id=”95F25D4A-D256-4158-96FE-010F599149CC”

xmlns=http://schemas.microsoft.com/sharepoint/

Title=”Demo Master Page”

Scope=”Site” Version=”1.0.0.0″ Hidden=”FALSE” Description=”This Feature contains the demo master page”>

<ElementManifests>

<ElementManifest Location=”elements.xml” />

<ElementFile Location=”MasterPages\demomasterpage.master” />

</ElementManifests>

</Feature>

Now see the attributes required to create this featue.xml
Id :This is the unique id for each feature. This can be created
Goto Tools tab in the visual studio and select Create GUID and create a new GUiD
Title :To specify the name for the feature .Name of the Feature title and the name of the containing folder should be same
Description : To specify the description of the feature
Scope : This is very important property as this property defines the scope of the feature.
There are 4 types of scope :
a) Farm b) WebApplication c) Site d) Web
If scope is site then feature is installed at site collection level and it will be available to the root site and subsites below it.
If scope is web then the scope of the feature is web..

Hidden : This property specifies if this feature should be visible in the feature collection.This is important if user wants to activate the feature from the command line utility (i.e. stsad.exe)

Feature.xml specify the feature attributes but the
Now next element is the ElementManifests.
This contains two tags

This tells the location of the element file which contains the actual implementation of the feature

This tells the location of any other files that is required during the feature installation.In this scenario this the location of master page which is going to deployed
Here MasterPages is the name of the folder where it is stored(same as feature folder)
Element.xml

<Elements xmlns=”http://schemas.microsoft.com/sharepoint/”>

<Module Name=”DemoMasterPage” Url=”_catalogs/masterpage” Path=”MasterPages” RootWebOnly=”FALSE”>

<File Url=”demomasterpage.master” Type=”GhostableInLibrary” />

</Module>

</Elements>

This file tells us what exactly has to be implemented
Inside the tag <Module set some attributes like
Name : , Url : this tells the location where master page has to be installed, Path: This gives the relative path of the master page file ,RootWebOnly : This property tells if this action has to be performed at only root web or it should be available to all the subsites.

<File tag gives information about the master page and it should be installed on the server
this tells SharePoint the name of the file it is going to put at the master page gallery. The type is “GhostableInLibrary” - this means the file is still going to be on the 12 hive and SharePoint is going to keep a Ghosted reference to the file. Please refer to article 3

http://sharepointmagazine.net/technical/customisation/developing-a-custom-master-page-master-pages-and-sharepoint-part-3-of-6 for more information about Ghosting. To install and activate the columns

Note : Copy the features folder in the 12/Template/Features folder in the file structure and then install and activate the feature

Through command line utility
Go to run and write cmd to open the command prompt
Go to the 12 hive folder
Command :
To install feature
Stsadm –o installfeature –name “” [-force]
To Activate feature
Stsadm –o activatefeature –name “” –url “” [-force]
Now the feature is installed and activated at a particular site collection. Go to the site settings and click on master pages there the newly installed master page will be available in the master page drop down.

Your Job is done !!!
Enjoy!!!

How to get the current logged in user in Event handler

Recently i faced a problem in event handler to do some operation for the current logged in user,but inside event handler SPContext object is null. So after some probe we found a way to get the current user object .

For this we need to get the HttpContext object inside the constructor of the event handler

Here is the sample code :

———————————————–

HttpContext current;

///

/// Constructor to get the current logged in user details

///

public ListEventHandler()

{

current = HttpContext.Current;

}

————————————————-

Now to get the login name of the current user use this code:

string currentUserLoginName = current.User.Identity.Name;

————————————–

So your job is done

Enjoy!!!

To restore a site on the same or different machine using the content db backup follow the steps given below:

Follow these steps :
  1. Create a new Web application on the destination server.
  2. Go to central admin –> content database . Click on the new web app content db.
  3. Remove the content db.
  4. Go to SQL server mgmt studio and create a new db with the same name as the content db backup you are having.
  5. After creation right click restore. Choose the backup file location. From the options tab choose ‘overwrite’.
  6. Restore this db backup.
  7. Go to central admin –> content database again and select ‘ add a content db ‘ to the web application.
  8. specify the name of the restored db.
  9. Done

Enjoy!!!

Programmatically Adding List viewer Web part(for document Library) on the page

Objective is to add the listviewer web part on the page programmatically. I have a document library for which i want to add the list viewer web part on any page.

Create a console application and paste the code

Code snippet

class Program

{

static void Main(string[] args)

{

SPSite site = new SPSite(”Site Url”);

SPWeb oSubWeb = site.OpenWeb();

oSubWeb.AllowUnsafeUpdates = true;

//Get the object of the page as SPFile on which we need to add the listviewer webpart

SPFile oFile = oSubWeb.GetFile(”default.aspx”);

//Create the object SPLimitedWebPart Manager

SPLimitedWebPartManager oWebPM = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared);

//Get the object of the list of which we are creatin the list viewer webpart

SPList oSubSiteList = oSubWeb.Lists["Shared Documents"];

//Create the object of ListViewer webpart

ListViewWebPart oListViewWP = new ListViewWebPart();

//Set the properties of the webpart

oListViewWP.ChromeType = PartChromeType.TitleOnly;

oListViewWP.Title = “Shared Documents”;

oListViewWP.ListName = oSubSiteList.ID.ToString(”B”).ToUpper();

//Define the zone in which webparts need to be added

oWebPM.AddWebPart(oListViewWP, “Zone 1″, 1);

}

}

Your job is done….

Enjoy!!!

If you find this post useful then please post your comments

Using SP Grid View inside Webpart

In this post I am using SPGrid view inside a webpart.

First we need to initialize the SPGrid view control in the Create Child control mehod and specify its properties

Use this code inside CreateChildControl method

—————————————————————

//Initialize the control

SPGrid CustomGrid;

CustomGrid = new SPGridView();

CustomGrid.Width = Unit.Pixel(700);

this.CustomGrid.ID = “Customgrid”;

//Specifying the Eventhandler for Paging

this.CustomGrid.PageIndexChanging += new GridViewPageEventHandler(CustomGrid_PageIndexChanging);

this.CustomGrid.AutoGenerateColumns = false;

//Specifying the grid properties

this.CustomGrid.PageSize = 10;

this.CustomGrid.BackColor = System.Drawing.Color.White;

this.CustomGrid.GridLines = GridLines.Horizontal;

//Allowing Paging on the Grid

this.CustomGrid.AllowPaging = true;

this.CustomGrid.EnableViewState = true;

this.CustomGrid.TemplateControl = null;

//Creating Boundfields in the Grid view

BoundField DealName = new BoundField();

DealName.DataField = “Name”;

DealName.ItemStyle.Width = Unit.Percentage(30);

DealName.ItemStyle.Wrap = true;

this.Controls.Add(CustomGrid);

CustomGrid.PagerTemplate = null;

—————————————————————–

Once the declaration and initialization of control is done we need to define the pagination of the SPGrid

This is the method for the pagination event

—————————————————–

// Method for Page indexing

void CustomGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

try

{

CustomGrid.PageIndex = e.NewPageIndex;

CustomGrid.DataBind();

}

catch (Exception ex)

{

}

}

Your job is done ..

Enjoy!!!