Tuesday, December 8, 2009

Migration SharePoint 2007 to SharePoint 2010

Prerequisites for migrating SharePoint 2007 site to SharePoint 2010:1. Check whether the packages (wsp features etc) in source server are same as in the target server (if not please install).
2. Check the web.config modifications made in the MOSS 2007 site (source site), if any do the same modifications on MOSS 2010 site (target site) accordingly.

Migration process:

The only process to migrate the site from SharePoint 2007 to SharePoint 2010 is the migrating contentDB of source site to target site.

Steps to follow for migrating ContentDB:

1. Take the backup of the source site contentDB and restore the same on target server.
2. Create the web application in SharePoint 2010, and then create the site collection (it doesn’t matter what site template you are using for creating site collection).
3. Once finished creating the SharePoint 2010 site, go to central administration --> Manage content databases --> select the web application you created for migration --> click on database --> check in the remove content database --> click ok

4.Add the restored database in the target site by using stsadm.exe in command prompt

Stsadm.exe –o addcontentdb –url “enter your url” –databasename “enter your db name”

5.Restart iis.

Monday, December 7, 2009

Hide the infopath form banner "Powered by infopath form services"

After the publishing the infopath form in the SharePoint Site. You will find a banner called "Powered by infopath form services" in at the bottom of infopath form.

Blow command explains how to customize the form banner-

Remove banner:
stsadm.exe -o setformserviceproperty -pn allowbranding -pv false

Add banner:
stsadm.exe -o setformserviceproperty -pn allowbranding -pv true

To check the weather the banner is set or not
stsadm.exe -o getformserviceproperty -pn allowbranding


hope this helps you very much.

Friday, November 20, 2009

CSS,Javascript not working in IE8 browser but working fine in IE7

The CSS and JAVSCRIPT which I implemented in Ramp Group (http://rampgroup.com) Website is working fine in IE7,Firefox,Google Chrome and safari.

However when it comes to IE8 it’s not working fine.
After a long research I found that we need to add a small meta tag in head tag

<meta http-equiv="X-UA-Compatible" content="IE=7"/ >

It tells to IE8 to build a website exactly same as IE7.

Tuesday, November 17, 2009

Windows PowerShell Execution Policy for 'AuthorizationManager check failed'

ERROR:
Command execution stopped because the shell variable "ErrorActionPreference" is set to Stop: Windows PowerShell snap-in "Quest.ActiveRoles.ADManagement" is loaded with the following warnings: Error loading the extended type data file: Quest.ActiveRoles.ADManagement, C:\Program Files\Quest Software\Management Shell for AD\Quest.ActiveRoles.ADManagement.Types.ps1xml : File skipped because of validation exception: "AuthorizationManager check failed.". There were errors in loading the format data file: Quest.ActiveRoles.ADManagement, C:\Program Files\Quest Software\Management Shell for AD\Quest.ActiveRoles.ADManagement.Format.ps1xml : File skipped because of validation exception: "AuthorizationManager check failed.".
At line:80 char:35 + if(-not $testsnapin){add-pssnapin <<<< -Name $SnapInName}


'AuthorizationManager check failed' means that initially we doesn't have permission to execute the Powershell Script to all users in the Sharepoint site because by default the execution policy is set to restricted.

To resolve the issue we need to got to 'ActiveRoles Management shell for Active Directory' command prompt and set execution policy to 'remotesigned' as shown below


C:\program files\Quest software\Management Shell for AD>set-Executionpolicy
cmdlet set-executionpolicy at command pipeline position 1
Supply values for the following parameters:
ExecutionPolicy: remotesigned
[PS] C:\Program Files\Quest Software\Management Shell for AD>

It will allows you to execute the script for all users who have permission to add the user in ADAM and for the SharePoint site.

WINDOWS POWERSHELL EXECUTION POLICIES:

The Windows PowerShell execution policies are as follows:

"Restricted" is the default policy.

Restricted

- Default execution policy.

- Permits individual commands, but will not run
scripts.

- Prevents running of all script files, including
formatting and configuration files (.ps1xml), module
script files (.psm1), and Windows PowerShell
profiles (.ps1).

AllSigned

- Scripts can run.

- Requires that all scripts and configuration files
be signed by a trusted publisher, including scripts
that you write on the local computer.

- Prompts you before running scripts from publishers
that you have not yet classified as trusted or
untrusted.

- Risks running unsigned scripts from sources other
than the Internet and signed, but malicious, scripts.

RemoteSigned

- Scripts can run.

- Requires a digital signature from a trusted
publisher on scripts and configuration files that
are downloaded from the Internet (including
e-mail and instant messaging programs).

- Does not require digital signatures on scripts that you have run
and that you have written on the local computer (not
downloaded from the Internet).

- Risks running signed, but malicious, scripts.

Unrestricted

- Unsigned scripts can run. (This risks running malicious
scripts.)

- Warns the user before running srcipts and configuration
files that are downloaded from the Internet.

Bypass

- Nothing is blocked and there are no warnings or
prompts.

- This execution policy is designed for configurations
in which a Windows PowerShell script is built in to a
a larger application or for configurations in which
Windows PowerShell is the foundation for a program
that has its own security model.

Undefined

- There is no execution policy set in the current scope.

- If the execution policy in all scopes is Undefined, the
effective execution policy is Restricted, which is the
default execution policy.

Monday, November 16, 2009

Create Users in ADAM using Windows PowerShell

In the previous post, I defined the Windows PowerShell .Now, I will show you how it is useful in real time.
In my scenario, I have an requirement to create an UI (User interface) for adding the User in ADAM. We can do it using c#, Vb.Net also. but if we use C# we need to install visual studio which will take of about 3GB from you hard disk.So, I prefer to use Powershell scripting language instead of using c# because it occupies less space than VS from the hard disk.

I searched in Google, I found a wonderful web part(iLoveSharePoint) to run the Power Shell script in SharePoint. Click here to download. I also found the CmdLets to add users in ADAM called Quest AD Management Shell.

AD Management Shell:

It is a PowerShell snap-In that allows you to add the users, groups in the ADAM (Active directory Application Mode) and AD in very handy. The cmdlets are from Quest Software.

How to use Quest Software:
  1. Download the file according to your system configuration.
  2. Download the provided Guide which gives you a brief description.
  3. Install the downloaded file.
After completing the installation, you will find "Active Roles Management Shell for Active Directory" command prompt (start-->All programs -->Quest Software -->Active Roles Management Shell for Active Directory) looks like

iLoveSharePoint:
  1. Download the iLoveSharePoint web part from the codeplex.
  2. Please follow the instruction provided in the downloaded file.
  3. copy the script provided below to add the user in ADAM.
Script to Create users in ADAM:

########## Initialize ############

## declare global variables and functions
$tbUserName = New-Object System.Web.UI.WebControls.TextBox
$button = New-Object System.Web.UI.WebControls.Button
$lbUserName = New-Object System.Web.UI.WebControls.Label
$lbuserPrincipalName = New-Object System.Web.UI.WebControls.Label
$tbuserPrincipalName = New-Object System.Web.UI.WebControls.TextBox
$lbMessage = New-Object System.Web.UI.WebControls.Label
$ErrorMessage = New-Object System.Net.WebException

############# Load ##############

## first time the OnLoad fires before CreateChildControls
function OnLoad
{

$lbUserName.Text = 'UserName'
$lbuserPrincipalName.Text = 'Email'
$lbMessage.Text = ''

# Check if GET Request (first request).
if($isPostBack -eq $false)
{
#$label.Text = 'GET request.'
}
}

####### 3. Create Controls ########

# create child controls
function CreateChildControls($controls)
{
$controls.Add($tbUserName)
$button.Text = 'Add User'
Subscribe-Event $button 'Click' 'OnButtonClicked'
$controls.Add($button)
$controls.Add($lbUserName)
$controls.Add($lbuserPrincipalName)
$controls.Add($tbuserPrincipalName)
$controls.Add($lbMessage)

}
function connect-ADAM{

# This allows the use of a windows account for ADAM athentication without granting the application pool account rights to ADAM
$passwd = convertto-securestring "provide your admin password here" -asplaintext -force
$adamcred = new-object -typename System.Management.Automation.PSCredential -argumentlist "provide your admin user",$passwd

#ADAM connection, please provide the server followed by port number of your ADAM

connect-QADService -Service localhost:65000 -Credential $adamcred


}
function New-User
{
param([String]$newlogonid,[String]$userPrincipalName)

# provide the password here for the new user
$newpassword = "password123$"

$adamconnection = connect-ADAM
New-QADUser -Name $newlogonid -UserPassword $newpassword -ParentContainer $usercontainer -userPrincipalName $userPrincipalName -Connection $adamconnection
}
####### Events ########

# handle control events
# subscribe to an event with "Subscribe-Event($control, 'eventName','callback function name')"
function OnButtonClicked($sender, $args)
{
$SnapInName = "Quest.ActiveRoles.ADManagement"
$testsnapin = $null
$testsnapin = get-pssnapin | where { $_.Name -eq $SnapInName}
if(-not $testsnapin){add-pssnapin -Name $SnapInName}

$usercontainer = 'CN=Users,CN=ADAMPartition,DC=rajkamal,DC=COM'
$userPrincipalName = $tbuserPrincipalName.Text
$newUserName = $tbUserName.Text

$connection = connect-ADAM

if(($newUserName -eq '') -or ($userPrincipal -eq ''))
{
$lbMessage.Text = 'Please provide the details'
}
else
{
$results = get-QADUser -SearchRoot $usercontainer -name $newUserName -connection $connection
$principalName= get-QADUser -SearchRoot $usercontainer -ObjectAttributes @{userPrincipalName = $userPrincipalName} -connection $connection

if(!$results)
{
if(!$principalName)
{
New-User -newlogonid $newUserName -userPrincipalName $userPrincipalName

$lbMessage.Text = 'User successfully added'
}
else
{
$lbMessage.Text = 'UserPrincipalName already exists'
}
}
else
{
$lbMessage.Text = 'User already exists'
}
}

$tbUserName.text = [string]::Empty
$tbuserPrincipalName.text = [string]::Empty

}

## render html
function Render($writer)
{
$writer.Write("<table><tr><td colspan='2'><b>Add Users in ADAM</b></td></tr><tr><td>")

$lbUserName.RenderControl($writer)

$writer.Write(":</td><td>")

$tbUserName.RenderControl($writer)

$writer.Write("</td></tr><tr><td>")

$lbuserPrincipalName.RenderControl($writer)

$writer.Write(":</td><td>")

$tbuserPrincipalName.RenderControl($writer)

$writer.Write("</td></tr><tr><td colspan='2' align='center'>")

   $button.RenderControl($writer)

$writer.Write("</td><tr><td colspan='2' style='color:red;font-weight:bold;text-align:center'>")

$lbMessage.RenderControl($Writer)

$writer.Write("</td></tr></table>")


}

Windows PowerShell

Windows PowerShell (WPS) is a .NET-based environment for console-based system i.e, it is an object-oriented programming language and interactive command line shell for Microsoft windows.
WPS is similar to Perl which includes more than 130 standard commands called cmdlets (Command-lets).

Powershell is available as a free download for windows XP, windows server 2003 and vista, where as in Windows server 2008 and Windows 7 includes additional option to install this feature.

Advantages of PowerShell:
  • It's not a compiled language.
  • It has a plug-in ecosystem with lots of 'libraries' for doing various domain specific things like copying files, playing with AD, Exchange.
  • It's the right tool for a different, slightly overlapping set of jobs.
  • It's a lot more powerful and consistent than CMD.EXE and other things evolved from command shells that needed to fit into 8K RAM.
  • For smaller task, it is more preferable.
Disadvatages:

It is not preferable for larger tasks.

Thursday, October 29, 2009

SharePoint coding tips and tricks

The elementary thing that SharePoint developers should consider is, the correct way of using SharePoint object mode, and how to apply general programming techniques (such as caching and threading) to the SharePoint platform specifically. Generally developers who write custom code for developing the SharePoint Application will counter some issues like performance, scalability. This article makes you easier to find and fix your problem areas in the code and can avoid known pitfalls using SharePoint object model.

These are some of the areas that developers should concern
· Disposing of SharePoint Objects.
· Performance concerns related to folders, lists and SPQuery objects.
· Exact way of using SharePoint data and objects efficiently.
· Using web controls and timer jobs.

Disposable SharePoint objects:

1. Developers who are working on the windows SharePoint service object model for developing new SharePoint applications have objects that inherited from the IDisposable interface.
2. This article serves as a guide to the proper procedures for handling and disposing of SharePoint objects that implement IDisposable interface.
3. Some of the primary objects are SPWeb class and SPSite class, created as managed objects.
4. Microsoft .NET requires objects that implement the IDisposable interface to properly cleanup the unmanaged resources by explicitly calling the Dispose () or Close () method when you are finished using them.
5. Internally, SPSite and SPSite both hold references to an "internal class Microsoft.SharePoint.Library.SPRequest" which holds on to unmanaged COM resources.

Coding techniques to ensure Object Dispose:
These are some of the techniques to ensure the Object Dispose
· Dispose Method
· Using Clause
· Try, catch and finally blocks

Dispose vs. Close Method:

Both of them are same, but the dispose method internally calls the close method. For the best practice, use Dispose method instead of using close method because SPWeb and SPSite Objects implements IDisposable interface, and standard .NET framework garbage collector call the dispose method to free any resources associated with the object from memory.
Using Clause

1. Using clause will automatically dispose the SharePoint Objects. You can greatly simplify the code with using clause.
2. Common Language Run Time will convert the using clauses to try, catch and finally block, and any objects that implement the IDisposable interface are disposed for you.

Note: SPContext objects are managed from SharePoint framework and need not be disposing separately.

Try, catch and finally block:

Whenever you need to handle the exceptions we obviously use Try, catch and finally blocks. Please don’t leave the catch block empty. Declare Dispose method in the finally block, and make a note that for best practice check null before disposing the SharePoint objects as shown below.

SPSite spSite = null;
SPWeb spWeb = null;
try
{
spSite = new SPSite ("http://server");
spWeb = spSite.OpenWeb ();
}
catch (Exception e)
{

}
finally
{
if(spSite != null)
{
spSite.Dispose();
}
if (spWeb != null)
{
spWeb.Dispose ();
}
}

Respose.Redirect, with try, catch and finally block and using statements:

1. The finally block executes after calls to Response.Redirect in the try block. Response.Redirect ultimately generates a ThreadAbortException.
2. When this exception is raised, the runtime executes all finally blocks before ending the thread.
3. However, because the finally block can do an unbounded computation or cancel the ThreadAbortException, there is no guarantee that the thread will end.
4. Therefore, before any redirection or transfer of processing can occur, you must dispose of the objects. If your code must redirect, implement it in a way similar to the following code example.
SPSite spSite = null;
SPWeb spWeb = null;
try
{
spSite = new SPSite ("http://server");
spWeb = spSite.OpenWeb ();

if (spSite != null)
{
spSite.Dispose();
}
if (spWeb != null)
{
spWeb.Dispose ();
}
Response.Redirect ("www.google.com");
}

catch (Exception ex)
{

}

finally
{
if (spSite != null)
{
spSite.Dispose();
}
if (spWeb != null)
{
spWeb.Dispose ();
}
}

Performance concerns related to folders, lists and SPQuery objects:

1. To retrieve the all items from list, please don’t use SPList.Items.
2. SPList.Items will retrieve all the items from folders, subfolders including all fields in the list.
3. To eradicate this Problem use SPList.GetItems(Query).
4. Getting Items by identifier, Please use SPList.GetItemById(int) instead of using SPList.Items.GetItemById().
5. To retrieve the list from the site, It is always preferable to get the list based GUID or url i.e. SPWeb.Lists[GUID] or SPWeb.GetList(strUrl) instead of using List Name i.e., SPWeb.Lists[strListName].

Conclusion:
· Please check whether your code dispose the SharePoint objects.
· Please check that your code cache objects properly.
· Please check that your code use thread synchronization when necessary.

If you consider these issues when you write your code, your SharePoint system will run more efficiently and your users will have a much better experience. You can also help to prevent unexpected failures and errors in your system.

Wednesday, October 7, 2009

Installation of ADAM in Microsoft Operating systems

Active Directory Application Mode (ADAM) is an LDAP directory service designed specifically for directory-enabled applications.
If we want to provide access to our SharePoint Site to external parties or clients without providing them a Windows Active Directory Account, ADAM will be crucial.

ADAM in different Microsoft Operating system:

  1. Windows server 2003: By default, w2k3 does not provide any ADAM installed in it.We need download the executeable file at http://www.microsoft.com/downloads/details.aspx?FamilyId=9688F8B9-1034-4EF6-A3E5-2A2A57B5C8E4&displaylang=en
  2. Windows server 2003 r2: We need to follow some steps as shown below
  • Open Add or Remove Programs from Control Panel.
  • Click Add/Remove Windows Components.
  • Click Active Directory Services under Components, and then click Details.
  • Select the Active Directory Application Mode (ADAM) check box under Subcomponents of Active Directory Services, and then click OK.
  • Click Next on the Windows Components page.

3. Windows server 2008: By default, they provided us the ADAM.

Go to start --> Adminstration Tools --> click Active Directory Light Weight Directory setup wizard.

Thats all...

c# difference between the CurrentUser and AllUsers["username"] in sharepoint

When I am trying to retrieve the sharepoint site sign in user details from SharePoint Peoples and user group, I have faced some confusions as discussed below.

For example consider that we need the email address of the current user.According to my requirement i used property shown below

SPContext.Current.Web.CurrentUser.EMail returns only the current Sign in User email address

and CurrentWeb.AllUsers[Properties.UserLoginName].Email also returns email address.

AllUsers returns all users who are either members of the site or who have browsed to the site as authenticatedmembers of the domain group in the site.

CurrentUser returns only the current sign in user details.

Conclusion:

  1. If we want to current user details, we can use both properties as shown above.
  2. If we want the user details of particular user other than current user we need to use the AllUsers property.

Monday, October 5, 2009

Electronic signature in Share Point Document library

DocuSign eSignature services has been helping several industries sign documents electronically, eliminating the need for printing/Faxing.
ESIGN Documents in SharePoint 2007 feature uses DocuSig to enable the SP users sign documents or send signature requests from a document library without downloading a copy.

Friday, September 18, 2009

Configure the FTP services

This step-by-step article describes how to install and configure a File Transfer Protocol (FTP) server for anonymous access

FTP depends on IIS (Internet Information Services), without IIS we cannnot configure FTP to the server.

1)Click Start, point to Control Panel, and then click Add or Remove Programs.
2)Click Add/Remove Windows Components.
3)In the Components list, click Application Server, click Internet Information Services (IIS) (but do not select or clear the check box), and then click Details.
4)Click to select the following check boxes (if they are not already selected):
Common FilesFile Transfer Protocol (FTP) ServiceInternet Information Services Manager
4)Click to select the check boxes next to any other IIS-related service or subcomponent that you want to install, and then click OK.
5)Click Next.
6)When you are prompted, insert the Windows Server 2003 CD-ROM into the computer's CD-ROM or DVD-ROM drive or provide a path to the location of the files, provide the path accordingly and then click OK.
7)Click Finish.
8)Open IIS (Internet Information Services) or else Go to run and type "inetmgr" to open IIS.
9)Expand Server_name, where Server_name is the name of the server.
10)Expand FTP Sites
11)Right-click Default FTP Site, and then click Properties.
12)Click the Security Accounts tab.
13)Click to select the Allow Anonymous Connections check box (if it is not already selected), and then click to select the Allow only anonymous connections check box. When you click to select the Allow only anonymous connections check box, you configure the FTP Service to allow only anonymous connections. Users cannot log on by using user names and passwords.
14)Click the Home Directory tab.
15)Click to select the Read and Log visits check boxes (if they are not already selected), and then click to clear the Write check box (if it is not already cleared).
16)Click OK.

Copy or move the files that you want to make available to the FTP publishing folder for access. The default folder is drive:\Inetpub\Ftproot, where drive is the drive on which IIS is installed.

Hopes this help you a lot....

Tuesday, September 8, 2009

SharePoint 2007 - Import from Spreadsheet to List

Import from Spreadsheet is the missing facet to the SharePoint 2007 List features. SharePoint let's a user create custom list from a spreadsheet, but lacks the ability to import data to an existing SP list. This feature developed in C# .Net and easy to install will do just that.

Here is the link http://spreadsheet2splist.codeplex.com

Friday, September 4, 2009

SharePoint web.config modification programmatically using c#

Here is the sample code to customize the web.config file for the SharePoint site programmatically
spSite = new SPSite(http://intranet.demo.com);
SPWeb spWeb = spSite.OpenWeb();
SPWebService service = SPWebService.ContentService;
SPWebApplication webApp = new SPSite("http://intranet.demo.com").WebApplication;
Configuration config = WebConfigurationManager.OpenWebConfiguration("/", spSite.WebApplication.Name);
XmlDocument doc = new XmlDocument();
doc.Load(configFilePath);
AppSettingsSection appSettings = config.AppSettings;
if (appSettings.ElementInformation.IsPresent)
{
XmlNode nodekey = doc.SelectSingleNode("configuration/appSettings/add[@key='key']");
if(nodekey == null)
{
SPWebConfigModification myModification = new SPWebConfigModification();
myModification.Path = "configuration/appSettings";
myModification.Name ="add[@key='userName']";
myModification.Sequence = 0;
myModification.Owner = "User Name";
myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
myModification.Value =
";
service.WebConfigModifications.Add(myModification);
}
}
/*Call Update and ApplyWebConfigModifications to save changes*/
service.Update();
service.ApplyWebConfigModifications();
As you can see, it is pretty simple and if you want to apply to the site spWeb.Site.WebApplication.WebConfigModifications.Add(MyModification)
If you want to apply to the whole farm
webApp.Farm.Services.GetValue().ApplyWebConfigModifications();
wenApp.Update();

Thursday, August 27, 2009

Create SharePoint Document Library programmatically using C#

We can create our own custom document library programmatically, here is the code shown below

SPSite site = SPContext.Current.Site as SPSite;
SPWeb web = site.RootWeb as SPWeb;
try
{ //Create a new library as the permanent library
Guid customListID = web.Lists.Add("CUSTOM DOCUMENT LIBRARY", "CUSTOM DOCUMENT LIBRARY", SPListTemplateType.DocumentLibrary);
web.Update();
}

Thursday, August 20, 2009

SharePoint Cannot complete this action error

When i am trying to count the CheckedOut items from SharePoint Document Library using c# code in visual studio as shown below

SPSite mysite = new SPSite("http://servername:portnumber");
SPWeb myWeb = mysite.OpenWeb();
myWeb.AllowUnsafeUpdates = true;
SPList Document = myWeb.Lists["Shared Documents"];
SPQuery query = new SPQuery();
query.Query ="<Where><IsNotNull><FieldRef Name='CheckoutUser' /></IsNotNull></Where>";
SPListItemCollection checkedOutItems= Document.GetItems(query);
Response.Write(checkedOutItems.Count);

I got the following error:
System.Runtime.InteropServices.COMException: Cannot complete this action

Resolution:

We need add the tag "<identity impersonate='true'/>" tag in the web.config file of the project in the visual studio.
This is because the ASP.NET doesnt allows you to read the outside documents i.e the documents(folders) are not in ASP.NET Application.So we need to keep impersonate = true in web.config file.

Hopes this helps you....

Monday, August 17, 2009

c# programmatically check the "<appSettings>" tag in web.config file of sharepoint sites

To check programmatically weather the appSettings tag is present in the web.config file of SharePoint sites, here is the code

using (SPSite site = new SPSite("http://servername:portnumber"))
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("/", mySite.WebApplication.Name);
AppSettingsSection appSettings = config.AppSettings;
bool isAppSettingsTagPresent = appSettings.ElementInformation.IsPresent;
}

hope this helps you very much...

Friday, August 7, 2009

Programmatically get the sharePoint List Url in C#

To get the Share Point list "url" based on list "Guid", here is the code shown below

SPSite Site = SPContext.Current.Site;
SPWeb web = Site.OpenWeb();
Guid listid = new Guid("{xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}");
web.AllowUnsafeUpdates = true;
SPList List = web.Lists[listid];
string url = SPContext.Current.Site.Url + "/" + List.RootFolder.Url;
Response.Write(url);
web.AllUnSafeUpdates = false;
web.Dispose();

Hopes this helps you a lot.

Thursday, August 6, 2009

Set "everyone" Permission to Folder using C# in Asp.Net

Here is the simple C# code to set "everyone" permissions to the folder .

string redirectionFolder = @"D:\test\subtest\";

FileSystemAccessRule everyOne = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl,AccessControlType.Allow);
DirectorySecurity dirSecurity = new DirectorySecurity(redirectionFolder, AccessControlSections.Group);
dirSecurity.AddAccessRule(everyOne);
Directory.SetAccessControl(redirectionFolder, dirSecurity);

Note:
If you get the error "Attempted to perform an unauthorized operation"

add the tag (<identity impersonate="true"/>) in your web.config file.

Steps to show the RSS Feed Data using SharePoint Designer

It is very simple to get data from RSS feeds using SP Designer.
I will show with a simple example.
Please follow the steps given below - (Explained with example)

1)Open the SP Designer, and open the site and the page where you want to show the RSS Feed data.
2)I am taking the RSS Feed Url of my blog (http://rajkamal29.blogspot.com/atom.xml).
3)In the right side of the SP Designer you will find the "Data Source Library" Toolbar,Go to "Server-side Scripts" Options and click "Connect to script or RSS Feed".

3)Now you will get an "Data Source Properties" window, thenn select "HTTP Get" method in the drop down and data command "Select", finally provide the RSS Feed Url of my blog as show above (http://rajkamal29.blogspot.com/atom.xml) in the "Url to a Server-side script" Section and click Ok.

4)Then select "Show Data" which is located when you click on the right arrow of the RSS feed connection as shown below.

5) Then you will go to the "Data Source Details" toolbar, where you will find all the Fields.
6) Select the "Fields" you want to display and click on the "Insert Selected Fields as.." button located on the top of the fields and click "Single Item View" tab.

7)You will find the data in the page( in Sharepoint Designer) as "Data form" webpart,then customize data form web part according your requirement as shown below.

Wednesday, August 5, 2009

Steps to remove Projects from Recent Projects in Visual Studio Start Page

To remove the Projects from Recent Projects in Visual Studio, there is no direct option to do this.We need to go to Registry Editor and Remove the Projects,follow the steps as shown below.
1) Go to Run in the start menu, type regedit
.
2) Go to HKEY_CURRENT_USER --> Softwares --> Microsoft --> VisualStudio --> 8.0 (if we want remove the recent projects in VS2005) or 9.0 (for vs2008) --> ProjectMRUList
3) Select and delete the Projects, which we don't want to show in the Recent Projects List of VS2005 or VS2008.

Next time when you start Visual Studio, the removed project through registry editor will not be listed on the start page.

Monday, August 3, 2009

C# Code to Update Document in SharePoint Document library

SPSite mySite =null;
SPWeb myWeb =null;

/* represents the current site */

using (mySite = SPContext.Current.Site)
{
using (myWeb = mySite.OpenWeb())
{

/* Modifes Windows SharePoint Services data in some way, you may need to allow unsafe updates on the Web site, without requiring a security validation. */

myWeb.AllowUnsafeUpdates = true;
Guid listId = new Guid(listID);
SPList documentLibrary = myWeb.Lists[listId];
SPListItem document = documentLibrary.GetItemById(itemID);

SPFolder oFolder = documentLibrary.RootFolder;

SPFileCollection collFiles = oFolder.Files;
SPFile oFile = null;

/* overwrite the file if exists in the document library */

oFile = collFiles.Add(document.Url, bytes, true);

SPListItem listItem = oFile.Item;

listItem["Col1"] = Value1;
listItem["Col2"] = Value2;

/* updates the versionsing of the document library also*/
listItem.UpdateOverwriteVersion();

myWeb.AllowUnsafeUpdates = false;
myWeb.Dispose();

}
}

Wednesday, July 15, 2009

Get QueryString Data using javascript

Assume the url is "http://localhost:portnumber/site/pages/page.aspx?Id=1

javascript function:

function getQueryProjectNum(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++)
{
var pair = vars[i].split("=");
if (pair[0] == variable)
{
return pair[1];
}
}
}

var Id= getQueryProjectNum("Id");

Friday, July 10, 2009

C# Code to identify the Mobile Device

Mobile Device:

Request.Browser["IsMobileDevice"] == "true";

BlackBerry:


Request.Browser["BlackBerry"] == "true" ;

iphone:

Request.UserAgent.ToLower().Contains("iphone");

Sample c# code:

if (Request.Headers["User-Agent"] != null && (Request.Browser["IsMobileDevice"] == "true" || Request.Browser["BlackBerry"] == "true" || Request.UserAgent.ToUpper().Contains("MIDP") || Request.UserAgent.ToUpper().Contains("CLDC")) || Request.UserAgent.ToLower().Contains("iphone"))
{
Response.Redirect("www.google.com");
}

Thursday, July 9, 2009

Render sites in mobile device with required view

1) By default, all the sites are designed with the width 980 pixels.
2) If we render the page with this width in the mobile, the user sees your page with miniscule, illegible letters and must zoom in to see the interesting parts, this is unacceptable.
3) Luckily, there is an option for us.
Just we need to use a small "meta" tag as shown below.

<meta name="viewport" content="width=device-width,user-scalable=yes" />

width = device-width (automatically adjust according the device width or else you can give your required width)
initial-scale = represents the Zoom level at which the user initially wants to see the page.
user-scalable = if the content exceeds the page, it represents wheather to show the scroll bar or not.

Stylesheet:

If you are providing any style sheet, we need to add the "media" property as shown below.

<link rel="stylesheet" href="StyleSheet.css" media="screen" type="text/css">




Render SharePoint List Items in ObjectList Mobile Controls

Generally, we use repeater control or datalist control to bind the SharePoint List Items.
When comes to Mobile Controls we use ObjectList Controls which works as repeater control.

Below is the sample code shows the procedure to bind the SharePoint List Items to ObjectList Control.

//Apply the styles for the Mobile Controls

<mobile:stylesheet id="mobileStyleSheet" runat="server">

       <mobile:style size="Small" name="Arial"></mobile:style>

   </mobile:stylesheet>

//Bind the SharePoint ListItem

<mobile:objectlist stylereference="ObjectList" id="olMobile" onprerender="olMobile_PreRender" runat="server">

          <devicespecific id="ds" runat="server">

               <choice>

                   <headertemplate>

                             Title

                   </headertemplate>

                   <itemtemplate>

                             <a href="javascript:void(0);"><%#Eval("Title") %></a>

                             <p><mobile:label id="lbDescription" runat="server"></mobile:label>

                             <mobile:link id="lnkUrl" runat="server">read more...</mobile:link></p>

                   </itemtemplate>

                   <footertemplate>

                          

                   </footertemplate>

               </choice>

          </devicespecific>

     </mobile:objectlist>

C# Code:

protected void Page_Load(object sender, EventArgs e)
{
using (SPSite spSite =new SPSite("http://servername:portnumber"))
{
SPWeb spWeb = spSite.OpenWeb();
spWeb.AllowUnsafeUpdates = true;
SPList spList = spWeb.Lists["ListName"];
SPQuery spQuery = new SPQuery();
spQuery.Query = "";
SPListItemCollection listitems= spList.GetItems(spQuery);
olMobile.DataSource = listitems.GetDataTable();
olMobile.DataBind();
spWeb.Dispose();
spWeb.AllowUnsafeUpdates = false;

}

}

protected void olMobile_PreRender(object sender, EventArgs e)
{
foreach (ObjectListItem item in olMobile.Items)
{
System.Web.UI.MobileControls.Link lnkUrl = (System.Web.UI.MobileControls.Link)item.FindControl("lnkUrl");
System.Web.UI.MobileControls.Label lbDescription = (System.Web.UI.MobileControls.Label)item.FindControl("lbDescription");

DataRowView drv = (DataRowView)item.DataItem;

lnkUrl.NavigateUrl = drv["Url"].ToString();
lbDescription.Text = drv["Description"].ToString();
}
}

Friday, July 3, 2009

Site Content type Gallery is Empty

After Creation of Site Collection we need to restart the iis (iisreset /noforce).
Unless and until if you didn't restart the iis you cant see the site content types in the site content type gallery.
So, make sure that the iis is resert as soon as site collection is created.

Tuesday, June 30, 2009

Programatically set permissions to the SharePoint Site

SPSite spSite= null;
SPWeb spWeb = null;

using(spSite = new SPSite("SiteUrl")
{
spWeb= spSite.OpenWeb();
spWeb.AllowUnSafeUpdates = true;
SPRoleAssignment spRoleAssignment = new SPRoleAssignment ("domain\\UserName","alias@domain.com","UserName","Test Message");
SPRoleDefinition spRoleDefinition = spWeb.RoleDefinitions.GetByType(SPRoleType.
Administrator);
spRoleAssignment.RoleDefinitionBindings.Add(spRoleDefinition);
spWeb.RoleAssignments.Add(spRoleAssignment);
spWeb.Dispose();
spWeb.AllowUnSafeUpdates = false;
}

Friday, May 29, 2009

The path specified cannot be used at this time. (Exception from HRESULT: 0x80070094)

I was receiving this exception every time when I tried to create a new web application (with a new application pool).

After receiving the message, I deleted the web application then I tried to open IIS to make sure the new application pool was also removed. IIS failed to open and I received the same message
"The path specified cannot be used at this time. (Exception from HRESULT: 0x80070094) "

To resolve this issue we need to follow the steps shown below:

1)IISREST.
2)Go to Services -->restart the "Windows SharePoint Services Timer".
3)if still fail ? restart windows server.

This is not a moss error but it is a windows 2003 error.

Friday, May 8, 2009

Sql function to Convert VARCHAR to INT

To Convert the value from varchar to int I created a small function as shown below:

Create Function [dbo].[CsvToInt] ( @Array varchar(1000)) returns @IntTable table (IntValue int)ASbegin
declare @separator char(1) set @separator = ','
declare @separator_position int declare @array_value varchar(1000) set @array = @array + ',' while patindex('%,%' , @array) <> 0 begin select @separator_position = patindex('%,%' , @array) select @array_value = left(@array, @separator_position - 1) Insert @IntTable Values (Cast(@array_value as int))
select @array = stuff(@array, 1, @separator_position, '') end
return end

Gradient Background using CSS without Images

1) The background-color is needed for Firefox as this seems to be unsupported in Firefox.
2) The rest of the code is self explanitory you have the start color and the finish color and the gradientType.
3) When the gradientType is set to 0, it is vertical from top to bottom.
4) When the gradientType is set to 1, it is horizontal from left to bottom.
5) If you are viewing this site within Internet Explorer or an IE based browser, the title bar has its
own gradient.
CSS:
body{background-color:#F8F8F8;filter: progid:DXImageTransform.Microsoft.Gradient(startColorStr='#FFCCFF' ,endColorStr='#8fffff' ,gradientType= '0' );width:400px;} body{background-color:#F8F8F8;filter: progid:DXImageTransform.Microsoft.Gradient(startColorStr='#FFCCFF' ,endColorStr='#8fffff' ,gradientType= '1' );width:400px;}
HTML:
<div>
This is the test message to understand how to get Gradient BackGround in IE using CSS without any need of Images.
</div>


Scroll bar for Repeater Control

Specify a height for Repeater Control by placing it in Panel or in div.If the records exceed the given height then Scroll bar should appear .We can achieve by using CSS given below.

Example:


.Panel
{
Height:200px;
width:100%;
overflow-y:scroll;
}

Query to Retrieve all the Tables,Views,Stored Procedure and Functions from Sql Server

Select * from sys.all_objects
Select * from information_schema.columns
Select * from information_schema.tables

Rounded Corners Using CSS and without Images

We can easily create Rounded Corners in the html Page with CSS, there is no need of images.
Just Copy and Paste the below CSS (Cascade Style Sheet) and Html in Page.




CSS:

.b1f, .b2f, .b3f, .b4f{font-size:1px; overflow:hidden; display:block;}
.b1f {height:1px; background:#0384ab; margin:0 5px;}
.b2f {height:1px; background:#0384ab; margin:0 3px;}
.b3f {height:1px; background:#0384ab; margin:0 2px;}
.b4f {height:2px; background:#0384ab; margin:0 1px;}
.contentf {background: #0384ab;width:100%}
.contentf div{margin-left: 5px;}
.itemCss{float:left;width:400px;padding:5px;color:#ffffff}

HTML:

<div style="width:400px;">
<b class="b1f"></b><b class="b2f"></b><b class="b3f"></b><b class="b4f"></b>
<div class="contentf">
<div class="itemCss">
This is the test message to understand how Rounded Corners obtained only with CSS.
There is no need of images to get Rounded Corners.
</div>
</div>
<b class="b4f"></b><b class="b3f"></b><b class="b2f"></b><b class="b1f"></b>
</div>

Thursday, May 7, 2009

Increase the Site Template and List Template Size

1) Generally to Create the Site Template for the Site ,the site shouldnot exceed more than 10MB.

2) If the Site exceeds it will prompt error message as shown below.

3) To resolve this problem we need to increase the Size of the Site Template by running this command shown below.

Command:

Site Template:
Default size = 10MB
stsadm -o setproperty -pn max-template-document-size -pv 20000000
(Where max-template-document-size is in Bytes)
Upper limit(Cap) = 500MB.


ListTemplate:
Default size = 10MB
stsadm -o setproperty -propertyname max-template-document-size -propertyvalue 50000000
(Where max-template-document-size is in Bytes)
Upper limit(Cap) = 500MB.







Steps to Change the DocIcons in SharePoint Sites

1)Download your Required DocIcon Image(DocIconName.gif) and save it in ("c:\Program Files\Common Files\Microsoft Shared\web server extensions\12\Template\Images") your mages folder.
2)Now Open the DOCICON.xml file located at "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\XML".
3)Add this "<Mapping Key="pdf" Value="pdf.gif"/>" ,this is the location where all the DocIcons are register.

Add Upload Attachement functionality for Comment List in SharePoint Blog Site

1) We have the option to add the Comment for the Post in the SharePoint Blog Site, but we dont have the option to Upload the Attachment for the Comment to the particular Post as shown below


2) If we want to add that Upload Attachment for the Comment, we need to edit the page http://SiteUrl/Lists/Posts/Post.aspx in the browser.

3) Then add the Content Editor WebPart below the Comments WebPart as shown below.


4) Now add the "table" tag as given below.


<table class="ms-toolbar" cellpadding="2" cellspacing="0" border="0" id="ctl00_m_g_4e9517cc_cbfa_4ac0_b45a_4f1f64696c60_ctl00_ctl01_ctl00_toolBarTbl" width="100%" >
<tr>
<td class="ms-toolbar" nowrap="true">
<table cellpadding='1' cellspacing='0'>
<tr>
<td class='ms-toolbar' nowrap>
<a href="javascript:UploadAttachment()" onclick="javascript:UploadAttachment();" accesskey="I" title="Add a Attachment" class='ms-toolbar'>
<img align='absmiddle' alt="Add a Attachment" src="/_layouts/images/attachtb.gif" style='border-width:0px;' width='16' height='16'>
</a>
</td>
<td class='ms-toolbar' nowrap>
<a id="ctl00_m_g_4e9517cc_cbfa_4ac0_b45a_4f1f64696c60_ctl00_ctl01_ctl00_toolBarTbl_RptControls_diidIOAttach" style="visibility:hidden;" href="javascript:UploadAttachment()">
</a>
<a href="javascript:UploadAttachment()" onclick="javascript:UploadAttachment();" accesskey="I" id="ctl00_m_g_4e9517cc_cbfa_4ac0_b45a_4f1f64696c60_ctl00_ctl01_ctl00_toolBarTbl_RptControls_diidIOAttach_LinkText" class='ms-toolbar'>Add a Attachment</a>
</td>
</tr>
</table>
</td>
<td width="99%" class="ms-toolbar" nowrap><IMG SRC="/_layouts/images/blank.gif" width=1 height=18 alt="">
</td>
</tr>
</table>

5) Finally, you added the Attachement for the Comments.



6) Looks Cool right :-)?

Integrate Silverlight in SharePoint

1) Initially we require html Page,Images and .XAP file of the Silverlight Application.

2) Upload the .xap file and Images Required into the SharePoint document library.

3) Add the Content Editor WebPart in the Page .

4) Copy the Script tag consists of javascript and html tags present in the body tag from the html page and Paste it in the Source Editor of the Content Editor WebPart, looks like as shown below

<script type="text/javascript">
function onSilverlightError(sender, args) {

var appSource = "";
if (sender != null && sender != 0) {
appSource = sender.getHost().Source;
}
var errorType = args.ErrorType;
var iErrorCode = args.ErrorCode;

var errMsg = "Unhandled Error in Silverlight 2 Application " + appSource + "\n" ;
errMsg += "Code: "+ iErrorCode + " \n";
errMsg += "Category: " + errorType + " \n";
errMsg += "Message: " + args.ErrorMessage + " \n";
if (errorType == "ParserError")
{
errMsg += "File: " + args.xamlFile + " \n";
errMsg += "Line: " + args.lineNumber + " \n";
errMsg += "Position: " + args.charPosition + " \n";
}
else if (errorType == "RuntimeError")
{
if (args.lineNumber != 0)
{
errMsg += "Line: " + args.lineNumber + " \n";
errMsg += "Position: " + args.charPosition + " \n";
}
errMsg += "MethodName: " + args.methodName + " \n";
}
throw new Error(errMsg);
}
</script>
<!-- Runtime errors from Silverlight will be displayed here.
This will contain debugging information and should be removed or hidden when debugging is completed -->
<div id='errorLocation' style="font-size: small;color: Gray;"></div>
<div id="silverlightControlHost">
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="810px" height="550px">
<param name="source" value="/Shared Documents/Trial.xap"/>
<param name="onerror" value="onSilverlightError" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="2.0.31005.0" />
<param name="initParams" value="ServiceUrl=http://ws27/Trial.Service/Service1.svc/" />
<param name="autoUpgrade" value="true" />
<a href="
http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">
<img src="
http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/>
</a>
</object> </div>

5) Provide the actual Path of the xap file in param tag shown above.

Create Custom Styles for the RichTextEditor in SharePoint

If we want to add the custom styles to Rich Text Editor present in (Content Editor web part) we need to follow the below steps:
  • Open the Custom Style Sheet which you are Created for the Site(by default core.css will apply for SharePoint Sites).
  • Add the Custom Style which Starts with ".ms-rteCustom-"
    For e.g: .ms-rteCustom-SquareBulletList{Font-family: arial; Line-style-type: square}.
    Now the above custom style will appear on Styles tab located in the Rich Text Editor toolbar as name “SquareBulletList” as shown below.

Note:The Custom Styles which we created will appear only when the text is selected in Rich Text Editor as shown above.
Images: "IMG.ms-rteCustom-yourstylename"
Links: "A:link.ms-rteCustom-yourstylename"
Numbered Lists: "OL.ms-rteCustom-yourstylename"
Un-Numbered Lists: "UL.ms-rteCustom-yourstylename"
Basic text: ".ms-rteCustom-yourstylename"
These are some of the Cusotm Style formats for RichTextEditor used in the Content Editor WebPart.