Showing posts with label MOSS. Show all posts
Showing posts with label MOSS. Show all posts

Monday, August 31, 2015

points to be noted on Event receivers in SharePoint 2013


properties.ErrorMessage is used for showing error in event handlers
properties.ListItem.Updateoverwriteversion() is used to overwrite version in list item, rather than adding a new version to the item it overwrites the existing one.
this.EventFiringEnable = false or True to stop or start the events on a list item, when ever you use "Updateoverwriteversion()" method inside a event we should set "this.EventFiringEnable= True" to stop the recursion 

Monday, April 27, 2015

Oracle LDAP and SharePoint 2013 integration

I have came across a post for oracle and SharePoint 2013 integration, i think this will help other too.

http://blogs.msdn.com/b/ronalg/archive/2014/04/14/sharepoint-2013-and-forms-based-authentication-configuration-for-open-ldap.aspx


Tuesday, March 11, 2014

1.difference between visual webpart and a standard webpart'
the SharePoint 2010 Visual Web Part is an ASCX web user control that is hosted inside a standard Web Part.

2.Difference between web user control and webpart
user control:
a.User controls must be compiled before use, which adds to the time it takes to load the control.
b.The Visual Web Developer designer provides support for designing the UI by using drag-and-drop operations that gives the control a consistent look-and-feel, which results in faster development.
Webpart:
a.Web Parts are precompiled and ready for use as soon as you need them.
b.The controls in Web Parts must be added by using code.

3.SharePoint site pages vs application pages
Site Pages:- Site Pages are Site or Web Scoped, User can customize Site Pages, Site Pages are stored in Content Database,
You cannot have custom code in Site Pages, Site Pages are Un-ghosted Pages.

Application Page:-
Application Pages are farm scoped, No customization can be done by the user, Application Pages are stored in WFE(Web Front End) in _layouts folder, You can have custom code in your Application Pages, Application Pages are Ghosted Pages.

4.Difference between WFE and application server
Microsoft SharePoint Foundation Web Application makes WFE in SharePoint farm

5.Difference between page library and site library
The Pages library is for storing Publishing Pages whereas the Site Pages library is for storing wiki and web part pages.
You only get the Pages library once the SharePoint Server Publishing feature is activated on the site. This library is usually used when you have requirements for content-centric pages that may use the scheduling, workflow and caching capabilities of SharePoint; such as in the case of public-facing websites. In a more collaborative scenario, you'd want to use the Site Pages library to create wiki and web part pages.

Saturday, March 16, 2013

What is Sandbox solutions and its limitations


Sandbox solution is a new feature introduced in SharePoint 2010. It's a secured wrapper around webparts and other elements with limitations. There is no thumb rule that every webpart in SharePoint 2010 belongs to Sandbox Solution. But it's recommended to develop webparts with Sandbox solution. It allows administrators to monitor the solutions and control as required. SharePoint Site Collection administrators can view the resource utilization of each solution and can block if it consumes too much resources. Usually when sites working slow, developers complain the server is slow whereas site/server administrators blame on Develepor code/solutions. Now Microsoft put a Full Stop to that. :)

Technically speaking SharePoint solutions run in seperate worker processes and not in w3wp.exe. So It doesn't require IIS Reset or Application Pool Recycling. Without disturbing the SharePoint site, Sandbox solutions can be deployed. Only thing while deploying new version of Sandbox solution over existing solution, SharePoint will display No Solution found error in Sandbox Webparts on the page. However within seconds sandbox solutions getting deployed and it'll start working. In SharePoint 2007, only farm administrators can install/deploy developer solutions. But Now site collection administrators can deploy solutions with web based interface. This reduces the dependency of Farm Administrator and improves rapid deployment.

Sandbox Processes
Here the processes which required for Sandbox solutions.
  1. SPUCWorkerprocess.exe - Sandbox Worker process service which is a Seperate Service Application which actually executes Sandbox code. It should be started in every farm to use Sandbox solutions.

  2. SPUCWorkerProcessProxy.exe - Sandbox Worker process proxy which is working as a proxy for Worker process and takes care of Sandbox code execution. It can also serve to other farms if configured. Basically it helps site administrator for load balancing.

  3. SPUCHostService.exe - Sandbox User Code Service takes care of user code in Sandbox amd it can be started in the farms where to use Sandbox solutions.
Sandbox Limitations
As I said before, Sandbox is a secured wrapper and it has restrictions on code to run in SharePoint environment. Few Key limitations which developers should know are listed below.
  1. No Security Elevation - RunWithElevatedPrivileges which runs the specified block of code in application pool account(typically System Account) context is not allowed in Sandbox code. SPSecurity class also not allowed to use in Sandbox.

  2. No Email Support - SPUtility.SendMail method has been blocked explicitly in Sandbox, However .Net mail classes can be used to send mails. Additionaly sandbox won't allow to read Farm SMTP address. So developers has to specify the SMTP address in code itself(may be some other workaround).

  3. No Support to WebPartPages Namespace - Sandbox won't allow to use Microsoft.SharePoint.WebPartPages namespace.

  4. No Support to external Webservice - Internet web service calls are not allowed to ensure security in Sandbox solutions. Allow Partially Trusted code also can't be accessed within Sandbox.

  5. No GAC Deployment - Sandbox solutions are not stored in File System(Physical path) and assemblies can't be deployed to Global Assembly Cache(GAC). But it's available on C:\ProgramData\Microsoft\SharePoint\UCCache at runtime. Note the ProgramData is a hidden folder.

  6. No Visual Webparts - Visual Studio 2010 by default won't allow to create Visual Webparts to deploy as sandbox solution. But with Visual Studio PowerTools extensions(downloadable from Microsoft MSDN website) Visual Webparts can be developed and deployed as sandbox Solutions.
SharePoint Online which is SharePoint environment provided by Microsoft to manage SharePoint Sites in internet accepts only Sandbox solutions. Because SharePoint Online sites are Windows Servers at Microsoft Datacenters, Microsoft won't allow GAC deployment or file system access. In future Sandbox solution will give more features for developers.

Deploying Master Pages & Themes via a Feature using Visual Studio 2010

Following this guide you’ll see the process that goes behind creating the feature which commonly be used to deploy branding items such as Master Pages, CSS, JavaScript, & Themes. If you plan to follow along just replace the steps with my name with whatever you wish.

Configure the Project

  1. Open Visual Studio 2010
  2. File -> New -> Project

  1. Select SharePoint -> Empty SharePoint Project
  2. Add Name: TomDaly.SharePoint.Branding (this is my standard structure)
  3. Add Location: C:\Projects\TomDaly

  1. Click OK
  2. Enter your test site for debugging purposes.
  3. Select ‘Deploy as farm solution’

  1. Click Finish

Adding the CSS / Image / JavaScript Files

Add CSS file

  1. Right Click on the Project -> Add -> SharePoint ‘Layouts’ Mapped Folder

  1. This created a folder which is mapped to the layouts

** These files in here are accessible through the web via http://YOURSITE/_layouts/TomDaly.SharePoint.Branding/
  1. Right click on Layouts\TomDaly.SharePoint.Branding folder -> Add -> New Item

  1. Select Web on the left, and Style Sheet on the right, and Name the file at the bottom.
(I typically use base.css or style.css for the foundation of my styles, but this is all up to you)
  1. Click Add

Add Images & JavaScript Folder

This would be the location for any images associated with the site css.
  1. Right Click on the Layouts\TomDaly.SharePoint.Branding folder -> Add -> New Folder

  1. Name the folder ‘images’

OPTIONAL STEP
  1. Repeat Step 1 & 2 for the JavaScript folder. (I typically call this folder ‘js’)

I usually include a JavaScript folder because most of the time I end up using jQuery somewhere on the site, this is where I store those files which I would reference on page or in the Master Page. Depending on how it’s needed.
These files would be accessible: http://YOURSITE /_layouts/TomDaly.SharePoint.Branding/js/JSFILESHERE

Setting up the Feature

  1. In your project Right click on Features -> Add Feature

This will create a feature with some default name of ‘Feature 1′, which we don’t want
  1. Select Feature1, Right Click -> Rename

  1. Rename the Feature to TomDaly.SharePoint.Branding (I typically name it to the same as the project name)

  1. Double Click on your Primary feature, in the main left hand window the properties should appear

  1. Give your feature a normal title name Title and Description, and scope it accordingly. (I usually scope my master pages to (Site) as they are normally used through the site collection

  1. Click Save

Renaming the WSP

This is really annoying to me so I always change it. When a .WSP is generated it will usually come out as Feature_Feature.wsp. I prefer just Feature.wsp.
1. Double Click on the primary Feature, the Properties should appear right below it.
2. Change ‘Deployment Path’
From: $SharePoint.Project.FileNameWithoutExtension$_$SharePoint.Feature.FileNameWithoutExtension$
To: $SharePoint.Project.FileNameWithoutExtension$

Adding the Master Page

1. Right Click on the Project -> Add -> New Item

2. In the left Installed Template column, Select SharePoint 2010
3. On the right select Module
4. At the bottom name the Module, Master Pages

5. Click Add
** You module will be added to your project **
6. Under the Master Pages Module, right click on Sample.txt and Delete It

7. Now Drag & Drag and Drop your Custom Master Page from another folder into the project, In the Master Pages Module

8. Double Click on the Elements.xml in the Master Pages Module

9. In the Elements.xml file, make the following changes to the <Module> line
Change
<Module
Name=MasterPages>


To
<Module
Name=MasterPages
Url=_catalogs/masterpage>


10. In the Elements.xml file, make the following changes to the <File> line
    a. add IgnoreIfAlreadyExists=True

    b. add Type=GhostableInLibrary

    c. remove MasterPages/ from the
Url=MasterPages/TOMDALY.master


So essentially this line
<File
Path=MasterPages\TOMDALY.master
Url=MasterPages/TOMDALY.master />


Changes to

<File
Path=MasterPages\TOMDALY.master
Url=TOMDALY.master
IgnoreIfAlreadyExists=True
Type=GhostableInLibrary />


11. Click Save

Adding Theme

This step will incorporate a theme into your project. How to generate the .thmx is not covered here but a simple way would be to export from PowerPoint or use ThemeBuilder to generate this file.
1. Right Click on the Project -> Add -> New Item

2. On the left Click SharePoint -> 2010
3. On the Right Select “Module”
4. Add Name: Theme

5. Click Add
6. In the Theme node, Delete Sample.Txt

7. Copy in you custom .thmx file
8. Double Click on the Elements.xml in the Theme Module

9. In the Elements.xml file, make the following changes to the <Module> line
Change
<Module
Name=Theme>


To
<Module
Name=Theme
Url=_catalogs/theme>


10. In the Elements.xml file, make the following changes to the <File> line
    a. add IgnoreIfAlreadyExists=True

    b. add Type=GhostableInLibrary

    c. remove Theme/ from the
Url=Theme/TomDaly.thmx


So essentially this line
<File
Path=Theme\TomDaly.thmx
Url=Theme/TomDaly.thmx
/>


Changes to

<File
Path=Theme\TomDaly.thmx
Url=TomDaly.thmx
IgnoreIfAlreadyExists=True
Type=GhostableInLibrary />


11. Click Save

Adding the Feature Receiver

This whole step is optional. Its sole purpose is to automatically turn on the branding on the sites and subsites, apply a theme, or apply search master pages to your site collection. NOTE: If you changed the scope then there is no guarantee that this code will work.
Please take some time to look through the code as there are different sections you might want to comment out or fill in. Say if you want to configure the Site Logo or an Alternative CSS file. If you not interested and just want a working project jump down to the END and in the summary there is a link to download the project.
1. Right Click your primary Feature, Select Add Event Receiver

** This will get added Right under your feature**
2. Double Click on the new file TomDaly.SharePoint.EventReciever.cs

5. At the very top Add the following using statements
using Microsoft.SharePoint.Utilities;

using System.Collections.ObjectModel;


7. Under the class declaration add these three string constants which contain the names of the masterpages and the theme.

So my master page name is TomDaly.master, my search master page which I don’t have a custom one for yet is minimal.master, and my Custom Theme is called TomDaly
8. Replace the public override void FeatureActivated, with

public override void FeatureActivated(SPFeatureReceiverProperties properties)

{

SPSite site = properties.Feature.Parent as SPSite;


if (site != null)

{

using (SPWeb topLevelSite = site.RootWeb)

{

//Get the relative path

string relativePath = topLevelSite.ServerRelativeUrl;

if (!relativePath.EndsWith(“/”))

{

relativePath += “/”;

}


//Get Theme collection from site and the them we want

ReadOnlyCollection<ThmxTheme> themes = ThmxTheme.GetManagedThemes(site);

ThmxTheme customTheme = null;

foreach (ThmxTheme theme in themes)

{

if (theme.Name == themeName)

{

customTheme = theme;

break;

}

}


//Apply branding to each web in the site collection

foreach (SPWeb web in site.AllWebs)

{

//Apply masterpage and logo

if (web.WebTemplate == “SRCHCENTERLITE” || web.WebTemplate == “SRCHCEN” || web.WebTemplate == “SRCHCENTERFAST”)

{

web.CustomMasterUrl = relativePath + “_catalogs/masterpage/” + searchMasterPage;

}

else

{

web.MasterUrl = relativePath + “_catalogs/masterpage/” + masterPage;

web.CustomMasterUrl = relativePath + “_catalogs/masterpage/” + masterPage;

}


web.AlternateCssUrl = “”;

web.SiteLogoUrl = “”;

web.UIVersion = 4;

web.Update();


//Also apply the theme

if (customTheme != null)

{

customTheme.ApplyTo(web, true);

web.Update();

}

}

}

}

}

9. Replace the public override void FeatureDeactivated, with
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)

{

SPSite site = properties.Feature.Parent as SPSite;


if (site != null)

{

using (SPWeb topLevelSite = site.RootWeb)

{

//Get the relative path

string relativePath = topLevelSite.ServerRelativeUrl;

if (!relativePath.EndsWith(“/”))

{

relativePath += “/”;

}


//Apply branding to each web the wen the site collection

foreach (SPWeb web in site.AllWebs)

{

//Apply default masterpage and logo

if (web.WebTemplate == “SRCHCENTERLITE” || web.WebTemplate == “SRCHCEN” || web.WebTemplate == “SRCHCENTERFAST”)

{

web.CustomMasterUrl = relativePath + “_catalogs/masterpage/minimal.master”;

}

else

{

web.MasterUrl = relativePath + “_catalogs/masterpage/v4.master”;

web.CustomMasterUrl = relativePath + “_catalogs/masterpage/v4.master”;

}


web.AlternateCssUrl = “”;

web.SiteLogoUrl = “”;

web.Update();


//reset the theme back to default

ThmxTheme.SetThemeUrlForWeb(web, null, true);

web.Update();

}

}

}

}

10. Click Save
11. Hit F6, or Build -> Build Solution … to ensure that everything is correct and ok. You should receive the “Build Succeed” in the bottom left corner



Changing the Site Url for Testing

Sometimes you want to create or re-use this package and you need to change the url of the site to deploy to.
1. Click on the project and in the Properties window you’ll notice the Site URL

2. Change that to your new site destination
3. Click Save

Deployment

If you’re testing on a development box, that visual studio is on then you can simply deploy through visual studio. Otherwise you’ll have to push out your solution with the .wsp file.

Deploy from Visual Studio

1. In the Build Menu, Select Deploy

OR

Getting the .WSP for manual deployment

1. In the Build menu, Select Build to ensure no errors
2. In the Build menu, Select Package to generate the .WSP file

3. The files will be in the project folder, and by default in the BIN\DEBUG
Either way once you deploy your solution should be available in the Site Collection Features Gallery as shown here

Summary

So that’s how you setup a project for deploying branding assets. This is the typical setup I use but can change from client to client depending on their needs.

When to use Allow Unsafe Updates

AllowUnsafeUpdates is set to true when you are trying to update the database as a result of the GET request.
Say you have a list and you want to update something, then you need to set AllowUnsafeUpdates = true for the web and after you have done you need to set it back to false.
AllowUnsafeUpdates = false protects from cross site scripting.
So if you need to allow your code to make some updates, you need to set allow unsafe updates to true and then back to false as soon you update.
SPList list= web.Lists["list name"];

SPListItemCollection items= list.GetItems();

web.AllowUnsafeUpdates = true;
foreach (SPListItem item in items)
{
     item["Field"] = "new val";
     item.Update();
}
web.AllowUnsafeUpdates = false;

Also refer following links for more idea.
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.allowunsafeupdates.aspx
http://blog.animesh.co.in/2010/03/sharepoint-spsiteallowunsafeupdates.html

Saturday, December 15, 2012

Setting Time stamp for a workflow in SharePoint Designer workflow


" Set Time Portion of Date/Time Field" workflow action - description, tips, limitations etc.workflow actions - Set Workflow Variable




Use this action to create a timestamp, and stores the output value in a variable. You can set the time in hours and minutes and add a current date, specific date or a lookup.

Allows you to set a date value with a specific value for hours and minutes

The date can field can be either today, a specific date or a lookup

Example scenarios:

1) Suppose you want to add a timestamp to any new customer orders that is added to an orders list. Instead of using the current time of the order received in the timestamp, you want to add a specific time so that you can have your workflow perform any action to all the new items with the same timestamp, such as routing orders to the warehouse.

2) You have a presentation at 9 a.m. on a particular day, and would like an email reminder. You can use this action to add the time to the date, pause the workflow till the day before the presentation and then have the workflow send you a reminder.

Thursday, November 29, 2012

Difference between Web Application,Site Collection,Site and sub site in SharePoint 


 Web Application
       -->Site Collection (SPSite)( A site collection cannot be physically seen in SharePoint)
              --> Site (SPWeb)
              --> Site (SPWeb)
      --> Site Collection (SPSite)
              --> Site (SPWeb)
                    --> Sub Site (SPWeb)
                    --> Sub Site (SPWeb)
The words between ( ) are the objects of the SharePoint API.

Thursday, November 22, 2012

Difference between ghosted and unghosted and what does it mean anyway?

This question is often asked by our SharePoint students.  To keep it short and sweet, ghosted means not customized and unghosted means customized. 
I'm sure everyone knows by now that SharePoint stores web pages like .aspx and other items in a few different places. 
  • The 12 Hive
  • The Content Database
  • IIS (in a virtual directory)
    • Some content in the 12 Hive
    • Some content nested under the InetPub folder
Well, let's say that there is a web page or other type of document that SharePoint uses that is stored in the 12 hive.  Like the default.aspx for example.  When it is first create during the install and placed in the 12 hive, it is considered to be ghosted.  An odd word for some that basically means that when the page needs to used it will be read from the folder somewhere in the 12 hive.  When your SharePoint site is created several entries are made in the Content Database (in SQL Server).  These entries tell SharePoint what Pages, List, Libraries, etc are associated with your SharePoint site.  But even though there is an entry in the database showing that your site uses the default.aspx page, it doesn't mean that the default.aspx page is stored in the database.  If you change the default.aspx (using SharePoint Designer for instance), you have customized the page and your version of the page will now be stored in the content database that stores the entries for that specific site.  The customized version of the default.aspx page is now considered unghosted for that specific site.
In other words, Ghosted pages become unghosted pages once a file has been modified.  There are several good reasons for this and there is more to the story. 

Difference between PowerShell and Stsadm in SharePoint

  • Windows PowerShell is built on the Microsoft .NET Framework and accepts and returns .NET Framework objects. Hence, can interact with .Net objects directly.
  • Here we use commandlets (cmdlet) instead of commands. Commandlet is a instance of .Net objects
  • We can automate the tasks using power shell scripts.
  • Windows PowerShell also gives you access to the file system on the computer and enables you to access other data stores, such as the registry and digital signature certificate stores.

Difference between webpart and user control in SharePoint


I feel the most important difference is that the webparts supports personalization which means that changes in the personal view will be stored per user basis. Also as Rob said, the user has the freedom to add/remove as per his need. On the other hand a usercontrol is more of a kind of static one. So you need to provide a functionality that is not required to be added and removed every now and then.

Wednesday, November 21, 2012

Splitting large Content DB into multiple content DBs in SharePoint/MOSS 2007

Very Exciting. Getting ready to split up a large content DB on a large enterprise level moss farm deployment. The idea is to distribute data that has grown over time into multiple content databases for performance and reliability. The plan is to use stsadm -o mergecontentdbs. However this is known to have implications and issues - http://support.microsoft.com/kb/969242. We are taking all necessary steps to avoid any problems. I'll update this post later on how our operation does.
 Update - Sorry for the late update guys. heres how it went.
 We had 2 tasks ahead of us. One was to move a content db from one database server to another in the cluster. The other was to split up a large content db on one of the servers into multiple content dbs.
Splitting the large content db into multiple content DB's:
 Microsoft recommended that we do not run the merge content db command on databases larger that 10 GB in size. So instead of moving out the larger site collections into new content databses, we decided to move all of the smaller site collections out instead. This would take much longer, but would be safer so we went that route.
  1. Make sure we stop all search crawls. This is important. Not pause but completely stop the search crawls. Let the running crawls complete and remove the schedule for all future crawls. If we do not do this, we take the risk of corrupting our search indexes.
  2. Create the new content databses
  3. Run stsadm -o preparetomove on the content db to be split
  4. Create a sites.xml using stsadm -o enumsitecollections on the source content database
  5. split up the sites.xml into manageable chunks containing the site colllections that we which to split out
  6. run stsadm -o mergecontent dbs on the source and destination content databases using the site.xml files created in step 5 to move the site collections from source to destination database to the destination content databases
  7. run stsadm -o databaserepair command on the source and destination databses to remove any orphan records - we had none
  8. test
we moved approximately 150 GB of data from a large content database into 5 diffenet new content databases. It took us approximately 18 hours including testing. After the maintennance, we improved page response times for the site collections. We also reduced app pool recycles for our web applications due to processes hitting their virtual memory limits. These almost seemed to dissapear after the maintennance. Overall we were very happy with the results.
Moving a content db from one server to another:
We had multiple large content databases on one server and we wanted to balance it out by moving a large content database from one server to another in the cluster.
  1. Run stsadm -o preparetomove on the content db to move
  2. detach the content db by running stsadm -o deletecontentdb
  3. using sql management studio, detach the content database from the server instance
  4. move the databse files from the source server to the destination server
  5. using management studio, re-attach the content database on the new sql server
  6. add the content database by ising stsadm -o addcontentdb
  7. Test
that was pretty much it. After our maintennance, we started our search crawls and reset the schedule. balancing out the databases also increased performance on our web applications.

Friday, November 16, 2012

Creating and Deploying Custom aspx Page as Feature and Solution Package


There are two ways to deploy a custom aspx page in SharePoint.

1. Using VseWss extensions project. Here you won't need to create a solution package manually. All the files need to create a solution package are created by the VS extensions itself. See the related Post Deploy Custom Css file in 12 hive. You can use same method to deploy your Custom aspx page.

2. The second way is creating a solution package around your asp.net webapplication so that the pages in the webapplictaion can be deployed in sharepoint. This requires you to manually create all the solution related files (I mean manifest.xml, feature.xml, elements.xml and .ddf file).


In this Post, we will create a solution package manually for a asp.net webapplication project, so that the custom aspx page created in asp.net web application can be deployed in SharePoint's Layouts folder.

Below are the Steps that you can follow :

1. Create a New WebApplication Project.

2. Create a new folder "MyCustomFolder" in the solution explorer and Add your custom aspx page (along with cs file) under it.

3. Add two more xml files in the same folder with names as elements.xml and feature.xml.

The Elements.xml File should look like below -

<elements xmlns="<a href=">http://schemas.microsoft.com/sharepoint/">
<module name="Pages" url="_layouts">
<file url="CustomPage.aspx" name="CustomPage.aspx" type="GhostableInLibrary"> </file>
</module>
</elements>
</div>

Note : Add Module name as “Pages” and url as ” _Layouts “


The Feature.xml File should look like below -

<feature id="79DD53E7-8719-45b0-8E25-C2450B3E3F14" title="Project.CustomPage" description="Custom Page" scope="Web" version="1.0.0.0" hidden="false" xmlns="http://schemas.microsoft/sharepoint/">
<elementmanifests>
<elementmanifest location="elements.xml">
<elementfile location="CustomPage.aspx"> </elementfile> </elementmanifest>
</elementmanifests>
</feature></div>


4. Now, Create another xml file in the Project and name it as manifest.xml

The manifest.xml should look like below -

<solution xmlns="<a href=">http://schemas.microsoft.com/sharepoint/" SolutionId="A5A9C1C2-4EBF-40db-935F-66085A9E0BE8">
<rootfiles>
<rootfile location="TEMPLATE\LAYOUTS\MyCustomFolder\CustomPage.aspx">
</rootfile>
<assemblies>
<assembly deploymenttarget="GlobalAssemblyCache" location="Project.CustomPage.dll">
<safecontrols>
<safecontrol assembly="Project.CustomPage Version=1.0.0.0, Culture=neutral, PublicKeyToken=a28586c97e90b41f" namespace=" Project.CustomPage" typename="*" safe="True"> </safecontrol>
</safecontrols>
</assembly>
</assemblies>
</rootfiles>
</solution>

Note : If you are using some code behind with your aspx page, then change the Inherit tag in the aspx page to inherit from the assembly of the project.

For e.g. change the tag to

Inherits="NameSpace.Class, NameSpace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2ef8d0c4bab8980b" Debug="true"

You dont need to deploy .cs file with the Project. The code is accessed via its .dll .

5. Finally Create the .ddf file ( its simply a text file with name as .ddf)

.ddf file would be something like below -

.OPTION Explicit ; Generate errors.Set CompressionType=MSZIP

.Set UniqueFiles=Off.Set

DiskDirectory1=Package

.Set CabinetNameTemplate=Project.CustomPage.wsp

manifest.xml

bin\ Project.CustomPage.dll

.Set DestinationDir=TEMPLATE\LAYOUTS\CustomPage.aspx

;sets the feature directory.

Set DestinationDir=CustomPageFolder

;adds the feature to the feature directory

MyCustomFolder\feature.xml

;adds the element to the feature

MyCustomFolder\elements.xml

I have created an empty folder in the Project with a name as “Package” to save the .wsp file in it.


6. Sign the project with a key (Project Properties -> "signing tab" and browse your .snk key) and Build the Project.

7. Now, Add and deploy the .wsp solution which is under Package Folder in SharePoint using stsadm commands.
What is the main difference between using SPListItem.Update() and SPListItem.SystemUpdate()?

Ans. Using SystemUpdate() will not create a new version and will also retain timestamps.

Impersonation in Sharepoint (RunWithElevatedPrivileges)

Although not recommended, there may be times when you need your code to perform certain functions that the current user does not have the necessary permissions to perform.

The SPSecurity class provides a method (RunWithElevatedPrivileges) that allows you to run a subset of code in the context of an account with higher privileges than the current user.
The premise is that you wrap the RunWithElevatedPrivileges method around your code. And also In certain circumstances, such as when working with Web forms, you may also need to set the AllowSafeUpdates method to true to temporarily turn off security validation within your code. If you use this technique, it is imperative that you set the AllowSafeUpdates method back to false to avoid any potential security risks.

Code example


{
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.OpenWeb();

//Using RunWithElevatedPrivileges

SPSecurity.RunWithElevatedPrivileges(delegate()
{
// Get references to the site collection and site for the current context.
// The using statement makes sures these references are disposed properly.

using (SPSite siteCollection = new SPSite(mySite.ID))
{

using (SPWeb web = siteCollection.OpenWeb(myWeb.ID))
{

web.AllowUnsafeUpdates = true;

try
{
//Your code
}


web.AllowUnsafeUpdates = false;

//siteCollection = null;
//web = null;

}

Thursday, November 15, 2012

What is a Field Control?

Ans.
Field controls are server controls that provide the basic field functionality of SharePoint. For example a Inputbox (single line text) to enter the title of the item. You can create your own FieldControl by inheriting classes from BaseFieldControl namespace.
Difference between Application Pages, Site Pages and Content Pages?

Application Pages - An application page is deployed once per Web server and cannot be customized on a site-by-site basis. They stay in 12 hive folder structure, mostly under layouts folder.

Site Pages - These are pages that make up the site interface and are specific to one site or site collection.They mostly get stored in the content database of the site collection.

Content Pages - Site Page which contains webpart or other custom components. This Page is stored in database. They mostly get stored in the content database of the site collection.

What are event receivers or event Handlers in SharePoint?


Ans.
Event Receivers or Event handlers are created to handle the basic actions or events against an item,list\library, a web or a site. There are two kinds of events in sharepoint.

Synchronous Events: Like Itemadding (not added yet), Uploading (document not uploaded yet) etc.

Asynchronous Events: ItemAdded (after item is added), Uploaded(after a document is uploaded)

Events receivers can be written to override an event for e.g. ItemAdded event to change the name of an Item once it is added.

You will normally, find it under C:\Program Files\Common Files\ shared\web server extensions\12\bin.

Run with elevated privileges in SharePoint,MOSS

(Gud one that I found in other blog)
In case you didn't know, there is a construct built into SharePoint that allows developers to create code that runs as the System Account instead of the logged in user, essentially giving that user Administrator Level Permissions in a confined space. I will go over the code required to do this below, but essentially you have a block of code within your larger project that needs the logged in user to have certain permissions that they may not have, and this small block of code will then be run as the System Account, giving it the permissions needed for the task at hand.
Well, at first thought everyone I have explained this to has the same questions and concerns, “Why would you ever want to do that?” or “That is a huge security risk!”.
I could never come up with a very good example to explain it and my attempts to reassure customers that the security risk is very minimal as the user will only have permission to do exactly what the developer lets them sometimes was not well understood.
Well I finally had a project that required me to do this, so I figured I would share it to give a fairly simple real world example.
Project Objective: Create an extranet to serve as a customer support site where users can log Service Requests, manage their account, order new products, etc. via the web or by phone.
This is fairly simple and something I have done several times for different customers, but this project had one difference. Service / Support Requests could be made by phone, where all of my other projects were strictly web oriented. Does anyone see the problem this raises yet? Well I eventually incorporated the Cisco phone system into the site to generate Service Requests, but that is not what I am talking about. With any system like this, it is vital that customers only have access to their own Service Requests (as in they cant view other user’s requests).
Typically, when using a SharePoint list one can turn on the settings in the Advanced Settings section of a List (seen below) so that users can only view and edit their own List Items. This is very handy and works very well when users are always the creator of their own items, but in this case when someone calls in, someone else will be creating the service request for them… see the problem? Well, I thought about trying to change the Created By field to the user that called in, but decided it would be a neat place to use the elevated permissions approach.

The Solution: So, this is the summary of what I did. I didn’t give any customers permissions to the Service Request List at all from within SharePoint. All access that customers had to that List was done through custom forms and web parts that made use of the elevated permission construct. This ended up being 3 forms and 3 web parts that used Elevated Permissions. Customers would use one form to create a Service Request, another to view it, another to edit it and then three web parts to display the contents of the list on various pages.
I added a custom text field to the list called Customer ID which would store each customer’s unique ID, detailing who each Service Request belonged to. The custom forms that users would use would populate this field upon creation by looking to see who the current user was, and looking up their ID in another List. Likewise when a member of the support staff was creating a service request received over the phone, they would fill in the Customer’s ID before creating it (The phone system was later used to automate this). This way, we are not relying on the Created Field to limit what each user is allowed to see.
Below I will go through the basics of how Elevated Permissions work and then show in more detail how I used it in my solution. Then in the next few days I hope to stick out a web part that incorporates it as well.
This is the basic code snippet you need to run with elevated permissions:
private void yourFunction()
{
      // Non-Elevated Permission Code Goes Here

      SPSecurity.RunWithElevatedPrivileges(delegate()
      {
            // Elevated Permission Code Goes Here
      });    

      // Non-Elevated Permission Code Goes Here
}
Pretty much everything you find online about this has code that is poorly explained, so hopefully I can do a decent job and make it easy. The code above is simple enough right? Well here is one place people routinely run into problems. If you are using an instance of SPWeb or SPSite before your Elevated Permission Code block, you won’t be able to use it. You need to get a new instance of the SPWeb or SPSite object to use once you enter the elevated block. Below is the code that I use to do this.
private void yourFunction()
{
      SPSite site = SPContext.Current.Site;
      SPWeb web = SPContext.Current.Web;

      SPSecurity.RunWithElevatedPrivileges(delegate()
      {
            using (SPSite ElevatedSite = new SPSite(site.ID))
            {
                  using (SPWeb ElevatedWeb = ElevatedSite.OpenWeb(web.ID))
                  {
                        // Code Using the SPWeb Object Goes Here
                  }
            }
       });
}
I am pretty sure that little tidbit cost me about a day the first time I tried to play with Elevated Permissions, so hopefully that will help some of you out. After that, it is really simple as you just put your code in the middle of it just like you would if you weren’t using the elevated permissions.
As further example, in my NewSR.aspx form that users go to when creating a new Service Request, I use a runWithElevatedPrivileges block in two functions. The first is a private function I call within the OnPreLoad() function called LoadData(). Inside this function I am populating drop down menus from data in a SharePoint list for the Priority of the service request and the products that are affected.
The second function with a runWithElevatedPrivileges block is my onSubmit() function that is called when a user clicks the submit button.

So it is actually pretty simple. The only other thing I am going to demonstrate is how I made the view and Edit Forms Secure. As you probably know, every List Item has an integer ID (.ID) and a unique guid ID (.UniqueID). Well, the custom forms I made for view and edit look in the querystring for a guid which it then uses to look up the Service Request. (If you can guess the guid of another service request, well you broke my security but it seems quite unlikely) There isn’t anything fancy about accessing the querystring to get the guid and look up the Service Request, but I thought it would be handy to store a link to the item within the item itself as an additional field. This makes it easy to email the user a link to view their service request among other things.
So I created a text field called Link and populated it as shown below.
private void yourFunction()
{
      SPSite site = SPContext.Current.Site;
      SPWeb web = SPContext.Current.Web;

      SPSecurity.RunWithElevatedPrivileges(delegate()
      {
            using (SPSite ElevatedSite = new SPSite(site.ID))
            {
                  using (SPWeb ElevatedWeb = ElevatedSite.OpenWeb(web.ID))
                  {
                        srList = ElevatedWeb.Lists["Service Requests"];
                        SPListItem newItem = srList.Items.Add();
                     
                        // Do stuff to create the list item

                        ElevatedWeb.AllowUnsafeUpdates = true;
                        newItem.Update();
                        Guid temp = newItem.UniqueId;
                        newItem["Link"] = "<DIV><a href=\"https://YourSite.com/_layouts/custom/ViewSR.aspx?ID=" + temp.ToString("d") + "\">View SR</a></DIV>";
                        newItem.Update();
                        ElevatedWeb.AllowUnsafeUpdates = false;
                  }
            }
       });
}
The tricky part here is having to call item.update() twice. You have to call it twice because the first time you call it is when the list item is actually created. Before then, it does not have a Unique ID to reference. So once it is created, you can grab the Unique ID, and populate the Link field with a HTML formatted URL that references the item and can be easily inserted into a HTML based email or a page that has a content editor web part CEWP with the JavaScript in it found here. You then call update the second time to save your link field.

The use of the link field and the JavaScript found above allows me to render links in a web part as shown above.
Well, hopefully this will be useful to someone – I think it would have saved me a day or so once upon a time when I first tried to do this.

SharePoint - Cannot convert a primitive value to the expected type 'Edm.Double'. See the inner exception for more details If y...

Ad