Sunday, November 29, 2009

Upload file from Document library to FTP Server

protected void PhotoUploadProcess()
{
try
{
// Get Current user and his last name
SPUser user = SPContext.Current.Web.CurrentUser;
username = user.Name;
smtpTo = user.Email;
strarray = username.Split(sepcomma);
userLastname = strarray[0].ToString();
//SPSecurity.RunWithElevatedPrivileges(delegate()
//{

//sharepoint site and web object
using (SPSite site = new SPSite(SPContext.Current.Site.Url.ToString() + "/Test"))
{
using (Microsoft.SharePoint.SPWeb web = site.OpenWeb())
{
SPList lstphoto = web.Lists["Test"];
web.AllowUnsafeUpdates = true;
string folderName;
int plenth = userLastname.Length - 1;
folderName = "Test" + "/" + userLastname.Substring(0, userLastname.Length - plenth);
SPFolder ImageFolder = web.GetFolder(folderName);


// Check whether sub folder is exist or not. If not, create folder in doc lib in user's last name first character format.
if (!ImageFolder.Exists)
{
SPFolderCollection myFolderCollection = web.GetFolder("PFPhyPic").SubFolders;
myFolderCollection.Add(userLastname.Substring(0, userLastname.Length - plenth));

}

// File input stream to read image and save it into document library
if (fileupload.PostedFile.ContentLength > 0)
{

Stream fStream;
SPFileCollection files = ImageFolder.Files;
fStream = fileupload.PostedFile.InputStream;
// Read file in a byte array
byte[] MyData = new byte[fStream.Length];
fStream.Read(MyData, 0, (int)fStream.Length);
strImagename = "123456.jpg";

SPFile filedata = files.Add(strImagename, MyData, true);
Int32 id = filedata.Item.ID;
strImagepath = SPContext.Current.Site.Url.ToString() + "/" + filedata.ServerRelativeUrl;

//update unique name
SPListItem lItemUser = null;
lItemUser = lstphoto.Items.GetItemById(id);
lItemUser["UniqueName"] = lblUID.Text;
lItemUser.Update();

lblMsg.Text = "Photo is uploaded successfully.";
btnCancel.Text = "Next =>";
// SPUtility.SendEmail(SPContext.Current.Web, false, false, useremailid, "Test Email", "Test");


//copy file to local server

try
{
System.IO.Directory.CreateDirectory("C:/FTPLOCALCOPY\\");
strlocalpath = @"C:/FTPLOCALCOPY/" + strImagename;

FileStream fs = new FileStream(strlocalpath, FileMode.Create);
BinaryWriter binaryWriter = new BinaryWriter(fs);

binaryWriter.Write(MyData);
binaryWriter.Close();

}
catch (Exception ex)
{

}

}

}
}
//});

}
catch (Exception ex)
{
lblMsg.Text = ex.Message.ToString();


}
}




public void uploadFileUsingFTP(string CompleteFTPPath, string CompleteLocalPath, string UName, string PWD, string domain)
{
try
{



//Create a FTP Request Object and Specfiy a Complete Path
FtpWebRequest reqObj = (FtpWebRequest)WebRequest.Create(CompleteFTPPath);

//Call A FileUpload Method of FTP Request Object
reqObj.Method = WebRequestMethods.Ftp.UploadFile;

//If you want to access Resourse Protected You need to give User Name and PWD
reqObj.Credentials = new NetworkCredential(UName, PWD, domain);

//FileStream object read file from Local Drive
FileStream streamObj = File.OpenRead(CompleteLocalPath);

//Store File in Buffer
byte[] buffer = new byte[streamObj.Length + 1];

//Read File from Buffer
streamObj.Read(buffer, 0, buffer.Length);




//Upload File to ftp://localHost/ set its object to nothing

reqObj.GetRequestStream().Write(buffer, 0, buffer.Length);

//Close FileStream Object Set its Value to nothing

streamObj.Close();

streamObj = null;



reqObj = null;
}
catch (Exception ex)
{
lblMsg.Text = ex.Message.ToString();


}

}

Wednesday, November 25, 2009

send an e-mail with attachment from SharePoint

One of the ways to send an e-mail from SharePoint as developer, is to make use of the “SPUtility.SendEmail” classes. But unfortunately I did not find any possibility to include an attachment with the help of these classes.

I have used SPAdministrationWebApplication for used shaerpoint email credential and send email with attachement through system.net class.


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using System.IO;
using Microsoft.SharePoint.Utilities;
using System.Net.Mail;
using Microsoft.SharePoint.Administration;
using System.Net;


//Get the Sharepoint SMTP information from the SPAdministrationWebApplication
string smtpServer = SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address;
string smtpFrom = SPAdministrationWebApplication.Local.OutboundMailSenderAddress;

//Create the mail message and supply it with from and to info
MailMessage mailMessage = new MailMessage(smtpFrom, smtpTo);

//Set the subject and body of the message
mailMessage.Subject = "Test";
mailMessage.Body = "test email .";

//Download the content of the file with a WebClient
WebClient webClient = new WebClient();


//Supply the WebClient with the network credentials of our user
webClient.Credentials = CredentialCache.DefaultNetworkCredentials;

//Download the byte array of the file
byte[] data = webClient.DownloadData(imagepath);

//Dump the byte array in a memory stream because
//we can write it to our attachment
MemoryStream memoryStreamOfFile = new MemoryStream(data);

//Add the attachment
//mailMessage.Attachments.Add(new System.Net.Mail.Attachment(memoryStreamOfFile, insert_filename_attachment, insert_content_type));
mailMessage.Attachments.Add(new System.Net.Mail.Attachment(memoryStreamOfFile, ImageName));
//, insert_content_type));


//Create the SMTP client object and send the message
SmtpClient smtpClient = new SmtpClient(smtpServer);
smtpClient.Host = "hostname";

//Delivery mothod which get attachement which size is more than 1 MB and immediately send email to user
smtpClient.Port = 2095;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtpClient.Send(mailMessage);



Hopy this stuff is useful for every developer.

Tuesday, November 24, 2009

Sharepoint Development: Object Model vs Web Services

When you've to develop a custom solution based on WSS/MOSS, I see that sometimes there are doubts on what technology to use in order to interop with the Sharepoint platform: should I use the Sharepoint Object Model APIs or should I use Sharepoint Web Services?

Use the Sharepoint Object Model if your code will be executed on a Sharepoint server farm machine. This is the best way if the final application will run on the Sharepoint server or if you're developing a Sharepoint WebPart.

To work with the Sharepoint Object Model, Right-click your Visual Studio project and add a reference to the Microsoft.SharePoint.dll located on the following directory:

C:\program files\common files\microsoft shared\web server extensions\12\isapi

If you're planning to develop a custom application that needs to interact with Sharepoint from a remote client, the best way is to use Sharepoint Web Services (the object model is not designed to support Remoting).

Saturday, November 14, 2009

Using SPQuery to filter lists by User & Group Column


If you want to filter a list based on the value in the look up field that is of type ‘Person or Group’, We have to consider the following options:
  • Filter by the User Name.
  • Filter by SPUser ID Property
  • Filter by Domain User account

Filter by the User Name:

By default the settings for the ‘Person or Group’ column will have the following settings.











The Show Field will have the “Name with Presence” selected.

When we run a SPQuery search on the list using the following code we will be able to filter the list based on the fullname of the user.

 using (SPSite oSite = new SPSite("http://moss:80"))

{

using (SPWeb oWeb = oSite.OpenWeb())

{

oList = oWeb.Lists["Project Tasks"];

SPQuery query = new SPQuery();

query.Query = "<Where><Eq><FieldRef Name='AssignedTo' /><Value Type='User'>Tushar Parikh</Value></Eq></Where>";

SPListItemCollection items = oList.GetItems(query);



}

}

Filtering by SPUser ID :

If you want to filter the list based on the SPUser ID then follow the steps below.

  • Add an additional attribute ‘LookupId’ for the queried field in your CAML query
<FieldRef Name='AssignedTo' LookupId='TRUE'/>

using (SPSite oSite = new SPSite("http://
moss:80"))

{

using (SPWeb oWeb = oSite.OpenWeb())

{

oList = oWeb.Lists["Project Tasks"];

SPQuery query = new SPQuery();

query.Query = "<Where><Eq><FieldRef Name='AssignedTo' LookupId='TRUE'/><Value Type='User'>7</Value></Eq></Where>";

SPListItemCollection items = oList.GetItems(query);

}

}


Filtering by Domain User Account :

If you want to filter the list based on the Domain User Account then follow the steps below.

  • Change the ‘Show Field’ Settings of the Person or Group lookup column to ‘Account’













Modify your code to include the domain account in the filter value.

using (SPSite oSite = new SPSite("http://
moss:80"))

{

using (SPWeb oWeb = oSite.OpenWeb())

{

oList = oWeb.Lists["Project Tasks"];

SPQuery query = new SPQuery();

query.Query = "<Where><Eq><FieldRef Name='AssignedTo' /><Value Type='User'>komal\tparikh</Value></Eq></Where>";

SPListItemCollection items = oList.GetItems(query);

}

}






Sunday, November 1, 2009

Feature 'GUID' for list template 'XXX' is not installed in this farm. The operation could not be completed

Feature 'GUID' for list template 'XXX' is not installed in this farm. The operation could not be completed.
We had a client receiving this message when accessing a site, and clicking Site Actions/Manage Content and Structure.

Install the Application Template Core Solution into the farm.

Link to Application Template Core Solution from Microsoft:
http://www.microsoft.com/downloads/details.aspx?FamilyId=C1039E13-94DA-4D7D-8CAE-3B96FA5A4045&displaylang=en

How to Install the Application Template Core solution (from Microsoft TechNet)
1. Download the Application Template Core solution to the server.
2. Double-click the .exe file to extract the files.
3. Open a Command Prompt window.
Note:

To open a Command Prompt window, click Start, point to All Programs, point to Accessories, and then click Command Prompt.
4. Type stsadm -o addsolution -filename \ApplicationTemplateCore.wsp, where is the location you extracted the Application Template Core files to, and then press ENTER.
5. Type stsadm -o deploysolution -name ApplicationTemplateCore.wsp -allowgacdeployment, and then press ENTER.
Note:

Additional attributes may be required based on your Windows SharePoint Services 3.0 configuration. For more information about available attributes, type stsadm -help deploysolution, and then press ENTER.
6. Type stsadm -o copyappbincontent, and then press ENTER.

Saturday, October 31, 2009

Move Wss 3.0 site to Moss 2007 -> error : version problem

Hi guys,

Today, i am trying to restore wss 3.0 site into moss 2007. My wss 3.0 site's version is 12.0.0.6421 and new moss server site's version is 12.0.4518. During restore time, i get error message regarding version.

Cause : Your backup is from a different version of Windows SharePoint Services and canno
t be restored to a server running the current version. The backup file should be
restored to a server with version '12.0.0.6421' or later.

Solution :
(1) Install wss 3.0 sp2
(2) Install Moss 2007 sp2
(3) Reset IIS

After installation, moss 2007 version is same displayed as wss 3.0.

(4) Restore you wss 3.0 site to moss 2007.
(5) Browser your web application.

SharePoint 2007 Versions

The first approach is to open a web browser and got to the site settings page (Site Actions > Site Settings > Modify All Settings).

The second approach is against the databases. Open SQL Server Management Studio, Connect to the server, new query, run the following:

SELECT [VersionId]
,[Version]
,[Id]
,[UserName]
,[TimeStamp]
,[FinalizeTimeStamp]
,[Mode]
,[ModeStack]
,[Updates]
,[Notes]
FROM [
SharePoint_Config].[dbo].[Versions]
WHERE VersionId = '00000000-0000-0000-0000-000000000000'
ORDER BY Id DESC

This returns (columns reduced for readability):

VersionId Version Id UserName Updates
00000000-0000-0000-0000-000000000000 12.0.0.6219 4 MOSS\user 3
00000000-0000-0000-0000-000000000000 12.0.0.4518 1 MOSS\user 2

The top row is the latest version. The query is performed on the SharePoint Configuration database. If you have called this database something instead of "SharePoint_Config" change the query to reflect this.

You can also look at the versions for Content Databases, by changing the database name. For example: FROM WSS_Content_MySites.[dbo].[Versions]

How to find the level of SharePoint you are running

Using SharePoint Central Administration Web site SharePoint HTML Site Settings admin pages or IIS Manager, on the web sites properties HTTP Headers tab, virtual servers once extended will show the following version numbers:
MOSS 20071 or WSS 3.0 Cumulative update (KB956056 & KB956057) 12.0.0.6327
MOSS 20071 or WSS 3.0 Infrastructure Update (KB951695 & KB951297) 12.0.0.6318
MOSS 20071 or WSS 3.0 post-SP1 hotfix (KB948945) 12.0.0.6303
MOSS 20071 or WSS 3.0 post-SP1 hotfix (KB941274) 12.0.0.6301
MOSS 20071 or WSS 3.0 post-SP1 hotfix (KB941422) 12.0.0.6300
MOSS 20071 or WSS 3.0 SP1 12.0.0.6219
MOSS 20071 or WSS 3.0 October public update 12.0.0.6039
MOSS 20071 or WSS 3.0 August 24, 2007 hotfix package 12.0.0.6036
MOSS 20071 or WSS 3.0 RTM 12.0.0.4518
MOSS 20071 or WSS 3.0 Beta 2 TR: 12.0.0.4407
MOSS 20071 or WSS 3.0 Beta 2: 12.0.0.4017
Office 12 (PDC image - pre-beta): 12.0.0.3111 (This version of Office does not have a support link in the Add/Remove programs dialog box).

1To confirm that a particular service pack is install on SharePoint Server you must either check the version numbers of specific dlls as specified in the related Microsoft Knowledge Based article or select the Show Updates check box in Add and Remove Programs.

WSS 2.0 SP3 6.0.2.8165
WSS 2.0 SP2 KB900929 + KB924881 6.0.2.8117
WSS 2.0 SP2 rollup KB900929 6.0.2.8000
WSS 2.0 SP2 6.0.2.6568
WSS 2.0 SP2 Beta = R2: 6.0.2.6551
WSS 2.0 SP1 + KB887981 6.0.2.6411
WSS 2.0 SP1: 6.0.2.6361
WSS 2.0 Unservice packed: 6.0.2.5530

To confirm that service packs are installed, especially with SharePoint Server 2007, goto Control Panel -> Add and Remove Programs
Select the product and then click: Click here for support. The versions will
be displayed as follows:


Windows SharePoint Services 3.0

Microsoft Office SharePoint Server 2007

post-SP1 hotfix (KB948945)

12.0.6303.5000

12.0.6303.5000
SP1

12.0.6219.1000

12.0.6219.1000
RTM

12.0.4518.1016

12.0.4518.1016
Beta 2 TR

12.0.4407.1005

12.0.4407.1005
Beta 2

12.0.4017.1006

12.0.4017.1006


Windows SharePoint Services 2

SharePoint Portal Server 2003

SP3

11.0.8173.0

11.0.8168.0

post SP2 rollup

11.0.8000.0

11.0.8126.2

SP2

11.0.7969.0

11.0.8126.0

R2 WSS SP2 beta

11.0.6551.0


SP1+KB887981

11.0.6411.0


With Service Pack 1

11.0.6361.0

11.0.6715.0

Unserviced pack

11.0.5608.0

11.0.5704.0

Server Error: http://go.microsoft.com/fwlink?LinkID=96177

In order to protect MOSS 2007 using DPM 2007 SP1, a few updates/ hotfixes need to be applied on MOSS 2007 server. One of the hotfix is "Windows SharePoint Services 3.0 post-Service Pack 1 hotfix package: January 31, 2008 (KB941422)". You may get details on this Knowledge Base from here: http://support.microsoft.com/kb/941422

After installing the update on MOSS 2007 server, you might experience that the MOSS web site is no more accessible but with a blank page and "Server error: http://go.microsoft.com/fwlink?LinkID=96177" on it. After some troubleshooting and we solve the problem by running this command on the MOSS 2007 front-end web server:

stsadm –o upgrade –inplace [-url <http://mosswebsite URL>] forceupgrade

PSCONFIG.EXE -cmd upgrade -inplace b2b -wait -force

IISRESET

This normally will happen even when you upgrade from WSS 3.0 to MOSS 2007 or install MOSS service pack 1 or Moss Service pack 2.

Friday, October 30, 2009

How does SharePoint automatically logged a user in?

Hi guys,

Here is the steps for automatic logged in sharepoint site when open it.

(1) Open IE browser.
(2) Go to Tools->Internet Options.
(3)Click on Security Tab.
(4)Click on Trusted Sites.
(5)Click on Custom Level. So security settings pop up is open.
(6)Go to User Authentication tab and select
Automatic Logon with current user name and password.

Wednesday, October 28, 2009

How to enable Search on your MOSS 2007 Site


Hi guys,

If you want to Enable Search facility on your sharepoint 2007 site,follow these steps:

Go to the Site Settings and under Site Administration Click on Search Visibility Link.










Update the seeting as shown on the attached image.


even after you enable the search visibility on your site and if you start search for a keyword on your site pages it will not work until the Crawling process will be run.

How can i Configure My Crawling process on MOSS 2007 ?

Open your central administration site: click on Share Services link under Share Services Administration.

Click on Search Settings -> Content Sources and Crawl Schedules -> Edit the Content Source which is exist.










Update your crawling services as you want and as per your organization needs.

Hope this helps....

Monday, October 12, 2009

Active search functionality in WSS using STSADM

stsadm -o spsearch -action start -databaseserver SERVERDB -databasename WSS_Search_SERVERDB

Tuesday, October 6, 2009

Show Currency with different locate in Sharepoint Data View Web Part

Suppose you’d like just a single DVWP to display numbers (either currency or regular numbers) in a different locale than the host site. This trick lets you do just that.

1. Open the page you need to customize with Sharepoint Designer. Switch to code view. Perform a search to find the tag xsl:decimal-format. Change the whole line with:

<xsl:decimal-format name="European" decimal-separator="," grouping-separator="." minus-sign="-" NaN="error" />

2. Now, locate your <xsl:value-of select=”@Total”/> and replace it as follows:
<xsl:value-of select="format-number(@Total, "€#.###,00;-€#.###,00", "European")"/>

WSS 3.0: When trying to search on sharepoint site, Getting message “No results matching your search were found.”

1. Symptom –
=============

–>When you are trying to perform search on your SharePoint site on your sharepoint server, you are getting following error message:

No results matching your search were found.
Check your spelling. Are the words in your query spelled correctly?
Try using synonyms. Maybe what you’re looking for uses slightly different words.
Make your search more general. Try more general terms in place of specific ones.
Try your search in a different scope. Different scopes can have different results.

–>Windows SharePoint help search is working fine and it gave results when we searched for “SharePoint”

–>Unable to get results on the SharePoint site

2. Cause –
==========

–>Issue due to windows Updates

3. Resolution –
================

–>We created a registry entry in the following location

HKLM\System\CurrentControlSet\Control\Lsa

–>Created a new DWORD key named “DisableLoopbackCheck” and modified the value to 1

–>We performed Full Crawl by the command

stsadm -o spsearch -action fullcrawlstart

–>We performed Search and it worked successfully

Tuesday, September 8, 2009

Retrive SPList Item using LINQ in Sharepoint

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace linqtest
{
public class SPLINQ : System.Web.UI.WebControls.WebParts.WebPart
{
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
base.Render(writer);
SPList taskList = SPContext.Current.Web.Lists["Tasks"];

// Get items, order by title alphabetically and assign to taskListItems
var taskListItems = from SPListItem tItem in taskList.Items
orderby tItem.Title
ascending select tItem;

foreach (SPListItem taskItem in taskListItems)
writer.WriteLine(taskItem.Title + "
\n");
}
}
}

Monday, August 24, 2009

Call ModalPopupExtender from Codebehind in .net

<head runat="server">
<title>Untitled Page</title>
<script>
function PopupModal ()
{
var modal = $find('modalPopupExtender1');

if (modal)
{
if (modal.show)
{
modal.show();
}
else
{
alert("nope!");
}
}
else
{
throw modal;
}
}
function onOk()
{
}
</script>
</head>
<body>
<form id="form1" runat="server">

<asp:ScriptManager runat="server" ID="ScriptManager1" EnablePageMethods="true" LoadScriptsBeforeUI="true"> </asp:ScriptManager>
<asp:Button ID="button1" runat="server" Text="Server_Click" OnClick="button1_Click" />
<asp:Button ID="buttonNull" style="display:none;" runat="server" />
<asp:UpdatePanel ID="updPanel1" runat='server'></asp:UpdatePanel>

<asp:Panel runat="server" ID="Panel1" Width="500" Height="500" style="display:none;"
BackColor="#fafad2" BorderColor="black" BorderStyle="solid" BorderWidth="1px">

<asp:panel runat="server" ID="Panel3" Width="100%" Height="27" BackColor="red">
DragHandle
</asp:panel>

<asp:Button ID="OKButton" runat="server"/>
<asp:button ID="CancelButton" runat="server" />
</asp:Panel>

<cc1:ModalPopupExtender ID="ModalPopupExtender" runat="server"
BehaviorID="modalPopupExtender1"
TargetControlID="buttonNull"
PopupControlID="Panel1"
BackgroundCssClass="modalBackground"
OkControlID="OkButton"
OnOkScript="onOk()"
CancelControlID="CancelButton"
DropShadow="true"
PopupDragHandleControlID="Panel3" />



Here is the code behind:

protected void button1_Click(object sender, EventArgs e)
{
//Do stuff

ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowPopup", "window.setTimeout('PopupModal()',50);", true);
}

Thursday, August 20, 2009

SharePoint 2010 Key Features

http://www.codeproject.com/KB/sharepoint/SharePoint_2010.aspx

Sharepoint 2010 has following new features
  • Better support for Internet facing sites
  • More security features & flexibility in managing permissions
  • Email management for users
  • Faster search
  • More storage options such as SAN, NAS, RAID etc. (currently only SQL)
  • Improved taxonomy management
  • Better Dashboards and reports
  • Records and archiving policies
  • Easy to use templates
  • More commands
  • Microsoft Groove is renamed as ‘SharePoint Workspace Manager’
  • Integration with other CMS products
  • Improved infopath form capabilities
  • More workflow types
  • Native support for Mozilla Firefox 3.0 and Opera
  • Better support for Mobile devices
  • Easy migration from SPS2003 and MOSS 2007
  • Snapshot Backup and Restore
  • Granular recovery at item level

Setup and Install SharePoint 2007 Server (MOSS) on Virtual PC

http://www.codeproject.com/KB/sharepoint/Install_SharePoint_on_VPC.aspx

Monday, July 20, 2009

Hiding the Search Box When Printing

* Open the master page in SharePoint Designer
* Add the following style either to a CSS file included in the master page or as a style within the master page itself:

@media print{
.HideForPrinting
{
display:none;
}
}

* Locate the delegate control used to display the search box and add the code shown in italics:

<asp:ContentPlaceHolder id=”PlaceHolderSearchArea” runat=”server”>
<span class=”HideForPrinting”>
<SharePoint:DelegateControl runat=”server” ControlId=”SmallSearchInputBox”/>
</span>
</asp:ContentPlaceHolder>

This defines a span that uses the style HideForPriting, the content of which will be hidden when the page is printed.

Change size of Rich Text Editing Control

When using the rich text column type in SharePoint lists the edit control has a fixed width of 384 pixels. This is often too small for easy editing.

If you need to change the width for a single form, open the form in SharePoint Designer and add a style defining ms-rtelong at the top of the content place holder in which the form is displayed with new dimensions, e.g.


<asp:Content ContentPlaceHolderId=”PlaceHolderMain” runat=”server”>

<style type=”text/css”>
.ms-rtelong {
width:700px;
height:600px;
}
</style>

Tuesday, July 14, 2009

How to access inetpub root folder using programatically in sharepoint

Here i have mentioned how to access inetpub root folder using object model.

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

string filename = web.Site.WebApplication.IisSettings[SPUrlZone.Default].Path.FullName.ToString() + @"\_app_bin\layouts.sitemap";

it will give filename like "C:\Inetpub\wwwroot\wss\VirtualDirectories\5858\_app_bin\layouts.sitemap"

Tuesday, July 7, 2009

Call Javascript on Page Load in Sharepoint Application Page

http://blogs.msdn.com/sharepoint/archive/2007/06/21/using-javascript-to-manipulate-a-list-form-field.aspx

Customize Edit Page and Redirect page after update using java script

1. In Sharepoint Designer take your EditForm.aspx and copy it.
2. Rename it
3. Open this new form and click on the PlaceHolderMain (leave your ListFormWebPart on the page)
4. In the ListFormWebPart scroll down the properties in the xml which describes the webpart and change to false. For some reason the form will not work unless you leave the original on the page.
4. Click on Insert->Sharepoint Controls->Custom List Form
5. Choose the appropriate List and select Edit Form
6. Sharepoint generates the form for you.

To customize the save button, find the following control on the page Sharepoint:SaveButton

1. Delete the SaveButton
2. Add

input type="button" value="Save" name="btnSave" onclick="javascript: {ddwrt:GenFireServerEvent('__commit;__redirect={Thanks.aspx}')}"

instead
3. This button allows the form to be saved and redirects to back to that page.

Friday, July 3, 2009

Delete Title Column in custom list sharepoint

Title column in custom list could be confusing in sharepoint. When you create any new custom list, Tital column is default column in list. You can't delete it but rename column name.

There is no way to Hide or Delete “Title” Column from List Settings User Interface. You can hide it by deselecting this column in your View but then you cannot edit the item as you wouldn’t have any Column linked to edit menu.

he only way to hide the “Title” Column is by writing a Custom List Definition, remember every Custom List MUST have this column as this is included in the Global ONET.xml (for Type “0″ List).

<Field ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" Name="Title" ReadOnly="TRUE" Required="FALSE" Hidden="TRUE" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="Title">
</Field>
<Field ID="{82642ec8-ef9b-478f-acf9-31f7d45fbc31}" Name="LinkTitle" Hidden="TRUE" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="LinkTitle">
</Field>
<Field ID="{bc91a437-52e7-49e1-8c4e-4698904b2b6d}" Name="LinkTitleNoMenu" Hidden="TRUE" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="LinkTitleNoMenu">
</Field>

Monday, June 29, 2009

World Clock Webpart


Today, I have released world clock webpart on codeplex.
You can download it from below link.
http://worldclock.codeplex.com/

After download, read document and installed it on MOSS Server.

It looks like below.








Friday, June 26, 2009

Free - SharePoint Text Size Zoom Feature

Sharepoint Text Size zoom functionality is useful in organization for low resolution projector.

Here i have mentions step to integrate with sharepoint site.
(1) Open Sharepoint Site in sharepoint Designer .
(2) Open _catalogs folder and create new folder "JS"
(3) Add new javascript into that rename as TextSize.js
(4)Open Javascript and add below code into js and save it.


function FontSizeChange_SetAllDocumentFontSize(size)
{
FontSizeChange_ChangeAllElements(document, size);

for(var i = 0; i < document.frames.length; i++)
{
FontSizeChange_ChangeAllElements(document.frames[i].document, size)
}
}

function FontSizeChange_RestoreDefault()
{


FontSizeChange_ReloadWindow(true);
}

function FontSizeChange_ReloadWindow(refresh)
{
if(refresh)
{
var url = window.location.href;
if(url.indexOf("#") == url.length - 1)
{
window.location.href = url.substring(0, url.length - 1)
}
else
{
window.location.href = url;
}
}
else
{
window.location.reload();
}
}
function FontSizeChange_ChangeAllElements(doc, size)
{
FontSizeChange_SetFontSizeByTagName(doc, "div", size);
FontSizeChange_SetFontSizeByTagName(doc, "span", size);
FontSizeChange_SetFontSizeByTagName(doc, "input", size);
FontSizeChange_SetFontSizeByTagName(doc, "a", size);
FontSizeChange_SetFontSizeByTagName(doc, "td", size);
FontSizeChange_SetFontSizeByTagName(doc, "th", size);
FontSizeChange_SetFontSizeByTagName(doc, "select", size);
FontSizeChange_SetFontSizeByTagName(doc, "font", size);
FontSizeChange_SetFontSizeByTagName(doc, "textarea", size);
FontSizeChange_SetFontSizeByTagName(doc, "IE:MENUITEM", size);
}

function FontSizeChange_Increase()
{
var font=document.getElementById('txtFont').value;
if(font <20)
{
document.getElementById('txtFont').value=parseInt(document.getElementById('txtFont').value) + 1;
}

var fontSize = font.toString() + "px";
FontSizeChange_SetFontSize(fontSize);


}

function FontSizeChange_SetFontSize(size)
{
FontSizeChange_SetAllDocumentFontSize(size);

}

function FontSizeChange_Decrease()
{
var font=document.getElementById('txtFont').value;
if(font > 8)
{
document.getElementById('txtFont').value=parseInt(document.getElementById('txtFont').value) - 1;
}

var fontSize = font.toString() + "px";
FontSizeChange_SetFontSize(fontSize);

}


function FontSizeChange_SetFontSizeByTagName(doc, tag, size)
{
var elements = doc.getElementsByTagName(tag);
for(var i = 0; i < elements.length; i ++)
{
elements[i].style.fontSize = size;
}
}


(5) Open Master page and add below script.

<script language="javascript" src="../JS/TextSize.js" type="text/javascript"></script>

(6) Also add below code into master page top corner.

<a title="Decrease Text Size" href="javascript:FontSizeChange_Decrease();"><asp:image runat="server" ID="imgdecrease" ImageUrl="_layouts/IMAGES/_size_small.gif" ></asp:image></a>

<a title="Default Text Size" href="javascript:FontSizeChange_RestoreDefault()"><asp:Image ID="imgdefault" runat="server" ImageUrl="_layouts/IMAGES/_size_medium.gif"></asp:Image></a>

<a title="Increase Text Size" href="javascript:FontSizeChange_Increase();"><asp:Image ID="imgincrease" runat="server" ImageUrl="_layouts/IMAGES/font_size_large.gif" ></asp:Image></a>

<input id="txtfont" type="hidden" value="12" >


Add image as per your requirement.

After complete this procedure, feature is look like below.






Cheers it and enjoy it.

Wednesday, June 17, 2009

Hide Sharepoint Site Action for non authentic user group

Sharepoint Site Action hiding is easy for non authenticate user. It is possible using sharepoint designer and after that only administrator's view Site Action button in sharepoint web application.

Open Sharepoint Designer and find SiteAction control in master page. Add
SPSecurityTrimmedControl before that.


<SharePoint:SPSecurityTrimmedControl runat="server" PermissionsString="ManageWeb" >


<SharePoint:SiteActions runat="server" AccessKey="<%$Resources:wss,tb_SiteActions_AK%>" id="SiteActionsMenuMain" ..........>
............
</SharePoint:SiteActions>

</SharePoint:SPSecurityTrimmedControl>

Tuesday, June 16, 2009

SharePoint DateTime Control Validation

<wssawc:DateTimeControl ID="dteDemo" runat="server" DateOnly="true" ></wssawc:DateTimeControl>


<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Please select activity date." ControlToValidate="dteDemo$dteDemoDate" ValidationGroup="Activity" Display="None"></asp:RequiredFieldValidator>

<asp:CompareValidator id="vdate" Display="None" runat="server" ControlToValidate="dteDemo$dteDemoDate" Type="date" Operator="dataTypeCheck" ErrorMessage="Please enter an valid date." vallidationGroup="Activity"></asp:CompareValidator>

Automatic take sharepoint site backup using batch file and scheduler

It is not possible to schedule sharepoint backup from sharepoint central admin site.
Below is process to take backup using batch file and after running schedule on specific time.

1. Open notepad and paste below code.

@echo off

@SET STSADM="c:\program files\common files\microsoft shared\web server extensions\12\bin\stsadm"

cd c:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN

@echo off

md "%DATE:/=_%"

stsadm -o backup -url "http://localhost:8080" -filename "E:\MOSS_Backup\%DATE:/=_%.bak"

echo completed

2. Save it as AutoBackup.bat (Change your site name )

Set Task schedular for this batch file and take backup on schedule time.


Tuesday, May 26, 2009

Send Document as Attachement Feature

Send document as attachment feature is useful in ECB menu to send email with current document as attachment.

You can download full code from codeplex.
http://trushar82.codeplex.com

Feature is look like below snap.







Monday, May 18, 2009

Custom Action link in listedit page in sharepoint

Feature.xml

<Feature Id="90CCFF3E-0874-441b-B430-1920BAF59B08"
Title="My Permission Link"

Version="1.0.0.0"
Scope="Web"
Hidden="false"
DefaultResourceFile="core"
xmlns="http://schemas.microsoft.com/sharepoint/">
<ElementManifests >
<ElementManifest Location="element.xml" />
</ElementManifests>
</Feature>


element.xml

<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

<CustomAction Id="39C18565-C185-4353-8025-E15859E3C4F3"
GroupId="Permissions"
Location="Microsoft.SharePoint.ListEdit"
Sequence="100"
Title="My Permission Link"
>

<UrlAction Url="_layouts/custom/MyRecycleBinItems.aspx" />

</CustomAction>
</Elements>


If you want add link in general settings then add
GroupId as GeneralSettings.

Thursday, May 14, 2009

Sharepoint Control - Object Model

Below is link which one use sharepoint object model as well as web part.

Sharepoint WebControl

Monday, May 11, 2009

Set current date in sharepoint DateTimeControl using Object Model

Below is a code to set current date in sharepoint dateTimeControl using object model.

dtdemodate.selectedDate=Now.Today.date.Tostring();

Export To Excel in Sharepoint

Today I have facing problem in my user control web part when i exported grid view data into excel.

Error is like "control not load at form server tag".

I have created new ASPX page and generate grid and write code for export to excel.
After put this control into sharepoint 12 hive folder like "_Layout".

I have added Page View web part in page and added property link like "http://localhost/_layout/exportToExcel.aspx".

So its working fine.
Put following code in ASPX page.

public override void VerifyRenderingInServerForm(Control control)

{

}

Tuesday, May 5, 2009

Upload File/Document in DocLibrary/List using Sharepoint Object Model

using (SPSite site = new SPSite("http://localhost"))
{

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

SPList list = web.Lists["MyList"];
web.AllowUnsafeUpdates = true;
SPListItem item = null;
item = list.Items.Add();

item["Title"] = "Test by Tushar";
string fileName = "";
if (File1.PostedFile != null)
{
Stream fStream = File1.PostedFile.InputStream;

byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
fStream.Dispose();

SPAttachmentCollection attachments = item.Attachments;
fileName = Path.GetFileName(File1.PostedFile.FileName);
attachments.Add(fileName, contents);

}

item["FileName"] = fileName;
item.Update();



}

Wednesday, April 8, 2009

Improve Sharepoint Site Performance using Blogcache

When a SharePoint is application is created, a web.config file is created in the application folder you specified. One of the entries inside the SharePoint element is BlobCache. By default, it looks like this:

<BlobCache location="C:\blobCache" path="\.(gif|jpg|png|css|js)$" maxSize="10" enabled="false" />

In order to improve the performance of your site, the BlobCache should be enabled.

<BlobCache location="C:\blobCache" path="\.(gif|jpg|png|css|js)$" maxSize="10" enabled="true" />

The maxSize attribute is in GigaBytes, so make sure you have enough room at the location.


See this article for more information about other caching techniques: http://blogs.msdn.com/ecm/archive/2006/11/08/how-to-make-your-moss-2007-web-site-faster-with-caching.aspx

Store Metadata in Property Bag for SPWEB

Property bags are a new feature of Windows SharePoint Services 3.0. A property bag enables you, as a developer, to add properties to objects in a Windows SharePoint Services site. Property bags are implemented by Windows SharePoint Services as a simple hash table of property names and values.

Many Windows SharePoint Services objects expose property bags, including:

SPWeb
SPFolder
SPFile
SPListItem

You can create and remove properties in a property bag programmatically, and you can modify the values assigned to properties. After updating a property in a property bag, you must invoke the Update() method so that the property value is persisted in the site database.

The following example shows code for adding a property to the property bag of an SPWeb object. The code also shows how to iterate through the property bag to retrieve key names and values.
Visual C# Code Example

// Obtain a reference to the current Web
SPWeb list = SPControl.GetContextWeb(Context);
// Enable updates to be made to the SPWeb object
list .AllowUnsafeUpdates = true;
// Add a property and update the property bag
list .Properties.Add("Project", "Development");
list .Properties.Update();
// Disable updates for the SPWeb object
list .AllowUnsafeUpdates = false;
// Iterate through the properties in the property bag
for each(System.Collections.DictionaryEntry webProperty
in
list .Properties)
{
this.Page.Response.Write(webProperty.Key.ToString()
+ " : "
+ webProperty.Value.ToString()
+ "
");
}


Once my metadata are added to my SPWeb properties, it's impossible to remove them.

Here is my code to delete :

site.Properties.Remove("mykey");

site.Properties.Update();

site.Update();

Tuesday, April 7, 2009

Bind List Items using SPDataSource using the object model

SPDataSource is a control that can be used to access data without needing declarative code


<%@ Register Tagprefix="SPwebControls" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>


<SPWebControls:SPDataSource runat="server" ID="dsPersonTitles" DataSourceMode="List"
SelectCommand="<Query><OrderBy><FieldRef Name='FirstName' /></OrderBy></Query>"

>

<SelectParameters>
<asp:Parameter Name="WebUrl" DefaultValue="{sitecollectionroot}" />
<asp:Parameter Name="ListName" DefaultValue="Employee" />
</SelectParameters>
</SPWebControls:SPDataSource>

<asp:DropDownList runat="server" ID="ddlPersonTitles" CssClass="title" DataSourceID="dsPersonTitles" DataTextField="FirstName" DataValueField="ID">
</asp:DropDownList>



Parameters

The SPDataSource Inherits from SPDataSourceView, basically a helper class for SPDataSourceView.
After a little Reflector-ing of SPDataSourceView I found these keys it is processing from from the parameter values collection.

  • webid
  • weburl
  • rootfolder
  • listid
  • listname
  • listitemguid
  • listitemid
  • folderid
  • nextpagedata
  • startrowindex
  • maximumrows

Monday, March 30, 2009

SharePoint Object Model

The SharePoint object model has four top-level objects:

* SPWeb (represents an individual site).
* SPSite (represents a site collection, which is a set of web sites).
* SPVirtualServer (represents a virtual server).
* SPGlobalAdmin (used for global administration settings).

In order to perform actions on data within a web, it is necessary to first get an SPWeb object (e.g. SPWeb MyWeb = SPControl.GetContextWeb(Context);)

The complete object model is grouped into lists, files (documents), security and administration:

* Lists - use these objects under the Microsoft.SharePoint namespace to view and edit data in SharePoint lists:
o SPList (basic list object for getting to list data).
o SPListCollection (collection of list objects).
o SPListItem (item/row in a list).
o SPListItemCollection (collection of list items).
o SPView (view of a SharePoint list).
o SPField (field/column in a list).
o SPListTemplate (template for a list).
* Files - use these objects under the Microsoft.SharePoint namespace to access document files in SharePoint sites:
o SPFile (file object).
o SPFileCollection (collection of files).
o SPFileVersion (version of a file).
o SPFolder (folder object).
o SPDocumentLibrary (document library object).
o SPDocDiscussion (discussions on a file).
o SPDocTemplate (used when creating a new file).
* Security - use these objects under the Microsoft.SharePoint namespace to edit access rights and security information:
o SPUser (user object).
o SPRole (site group object).
o SPGroup (cross-site group object).
o SPPermission (assigned permissions).
o SPRightsEnumeration (available permissions).
* Administration - use these objects under the Microsoft.SharePoint.Administration namespace to edit server-wide administrative settings.
o SPGlobalAdmin (top level administration object).
o SPVirtualServer (virtual Server object).
o SPQuota (storage/user quota limit object).
o SPGlobalConfig (configuration options).
o SPSiteCollection (collection of sites on a virtual server).

In terms of mapping the user interface onto the object model terminology:

* Site Collection = site.
* Site = web.
* Top-level site = rootweb.
* Subsite = subweb.