Saturday, October 25, 2008
Copy Document Library file into local server using event handler
{
try
{
//Copy Document Library file into local server using event handler
base.ItemAdded(properties);
DisableEventFiring();
SPWeb web = properties.OpenWeb();
web.AllowUnsafeUpdates = true;
SPList ilist = web.Lists[properties.ListId];
SPFolder folder = web.GetFolder(properties.ListTitle.ToString());
foreach (SPFile x in folder.Files)
{
if (properties.ListItemId == x.Item.ID)
{
string strpath = @"D:/Trushar/" + folder.Name.ToString() + "/" + x.Name.ToString();
//FileStream fs = new FileStream(@"D:/Trushar/MyDoc/Test1.jpg", FileMode.Create);
FileStream fs = new FileStream(strpath, FileMode.Create);
BinaryWriter binaryWriter = new BinaryWriter(fs);
byte[] fileData = (byte[])x.OpenBinary();
binaryWriter.Write(fileData);
binaryWriter.Close();
break;
}
}
EnableEventFiring();
}
catch (Exception ex )
{
}
}
Friday, October 24, 2008
How to register your custom events in MOSS 2007
1) Ensure that the assembly implementing the custom event handlers in strongly typed
2) Ensure that your custom event handlers strongly typed assembly has been registered in the GAC of the server (or on each server on a web farm).
Once you have checked the pre-requisites you can write a Console application to do your job. An example is as below:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
namespace trusharWebsite.Website.RegisterEventHandlers
{
// Console application to register custom event handlers on a specific list called "Comments" on the website
class Program
{
static void Main(string[] args)
{
SPSite curSite = new SPSite("http://trushar/trusharBlog");
SPWeb curWeb = curSite.OpenWeb();
SPList commentsList = curWeb.Lists["Comments"];
string asmName = "trusharWebsite.WebSite.EventHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=342fb345e6f432a";
string className = "trusharWebsite.WebSite.EventHandler.AddmyItemHandler";
commentsList.EventReceivers.Add(SPEventReceiverType.ItemAdding, asmName, className);
commentsList.EventReceivers.Add(SPEventReceiverType.ItemUpdating, asmName, className);
}
}
}
Thursday, October 23, 2008
Update WSS 3.0 User Profile Programmatically
In WSS 3.0, there is a special list ‘User Information List’ for user’s profile information. When a user is added to the Sharepoint site, a list item is automatically created in this list. To update the user’s information in ‘User Information List’, for instance, to update the user’s photo, I am using following code and it works fine:
SPList list = web.Lists["User Information List"];
SPUser u = web.SiteUsers[“domain\\user1”]
.
it[“Picture”] =”http://sharepointApp/sites/
it.Update();
Also, you are able to add a custom field to user profile like this:
SPList list = web.Lists["User Information List"];
if (!list.Fields.ContainsField("
{
list.Fields.Add("Favorites", SPFieldType.Text, false);
list.Update();
}
Saturday, October 18, 2008
Adding your own Administration Pages to Site Settings or Central Administration
For this you need a Feature and a definition of the new menu item to be added and where it links to.
<?xml version="1.0" encoding="utf-8"?>
<Feature Id="34251A34-3B03-4149-94A3-A04C5F99E251"
Title="My Administration Link"
Description="Link to administration page."
Version="12.0.0.0"
Scope="Web"
Hidden="FALSE"
DefaultResourceFile="core"
xmlns="http://schemas.microsoft.com/sharepoint/">
<ElementManifests>
<ElementManifest Location="elements.xml" />
</ElementManifests>
</Feature>
Element.xml file is as below :
<?xml version="1.0" encoding="utf-8"?>
<Elements
xmlns="http://schemas.microsoft.com/sharepoint/">
<CustomAction
Id="ManageMySettings"
GroupId="SiteCollectionAdmin"
Location="Microsoft.SharePoint.SiteSettings"
RequireSiteAdministrator="TRUE"
Sequence="45"
Title="Manage My Settings">
<UrlAction
Url="_layouts/MyAppSettings.aspx" />
</CustomAction>
</Elements>
This elements.xml file adds a link to the Site Settings Page (by setting the Location attribute), under the Site Collection Admin area (specified by the Group ID) and requiring Site Administrator Access to get to. The UrlAction element specifies where the link goes (in this case to an aspx page in _layouts).
I can also insert links into the Central Admin area if needed just by specifying a different CustomAction:
<?xml version="1.0" encoding="utf-8"?>
<Elements
xmlns="http://schemas.microsoft.com/sharepoint/">
<CustomActionGroup
Id="Mine"
Location="Microsoft.SharePoint.Administration.ApplicationManagement"
Title="My Applications"
Sequence="100" />
<CustomAction
Id="MyAppSettings"
GroupId="Mine"
Location="Microsoft.SharePoint.Administration.ApplicationManagement"
Sequence="11"
Title="My App Settings">
<UrlAction
Url="/_admin/AppSettings.aspx" />
</CustomAction>
</Elements>
SharePoint 2007 Forms Authentication with sqlserver Membership
I have read this article and it is good for form authentication.
http://weblog.vb-tech.com/nick/archive/2006/06/14/1617.aspx
http://www.andrewconnell.com/blog/articles/HowToConfigPublishingSiteWithDualAuthProvidersAndAnonAccess.aspx
http://weblog.vb-tech.com/nick/
http://www.chandima.net/Blog/archive/2007/02/15/how-to-setup-and-configure-forms-based-user-administration-feature-release-1-0-beta.aspx
http://www.codeproject.com/KB/sharepoint/FBA.aspx
Friday, October 17, 2008
Validating Date field in SharePoint through Javascript
function PreSaveAction()
{
var date1 = getTagFromIdentifierAndTitle("INPUT","DateTimeFieldDate","Contract Date");
var date2 = getTagFromIdentifierAndTitle("INPUT","DateTimeFieldDate","Contract End Date");
var arrDate1 = date1.value.split("/");
var useDate1 = new Date(arrDate1[2], arrDate1[1]-1, arrDate1[0]);
var arrDate2 = date2.value.split("/");
var useDate2 = new Date(arrDate2[2], arrDate2[1]-1, arrDate2[0]);
if(useDate1 > useDate2)
{
alert("The end date cannot happen earlier than the start date");
return false; // Cancel the item save process
}
return true; // OK to proceed with the save item }
How to get details error page instead of "An unexpected error has occurred" in MOSS 2007?
To get detail asp.net error page, you just need to do couple of changes in web.config file
SafeMode MaxControls=“200“ CallStack=“false“…
to…
SafeMode MaxControls=“200“ CallStack=“true“…
You will also need to set custom errors to 'Off' .
customErrors mode=“Off“
You will no longer see the “An unexpected error has occurred” error page and instead you get a lovely ’standard ASP.Net error page’ with the stack trace and everything…development has got that little bit easier!!
Saturday, October 11, 2008
STSADM Operation Command
http://blogs.technet.com/josebda/archive/2008/03/15/complete-reference-of-all-stsadm-operations-with-parameters-in-moss-2007-sp1.aspx
Thursday, October 9, 2008
Renaming a MOSS Server
- Open Central Administration, "Operations" Tab, "Alternate access mappings" link
- Modify each mapping item to reflect your newly chosen server name
- Open a command prompt window
- cd "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN"
- stsadm -o renameserver -newservername
-oldservername - Reboot the server NOW.
- After reboot, open command prompt
- cd C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN
- stsadm -o updatefarmcredentials -userlogin
-password - iisreset /noforce
- Check all application pool identities in IIS, update where the old machine name is still there.
- If you already have a search index drop this, and rebuild it
The use of SPContext
When building custom web parts for Windows SharePoint Services V3. You can use the SPContext object to get for instance the site or web from the current context. But that's not all you can get from SPContext. You can also get the listitem and the webfeatures.
In WSS V2 you would use SPControl.GetContextSite() or SPControl.GetContextWeb() but that's a lot less flexible and it's slower as well.
A couple of different uses of SPContext are shown below:
*************************************************************************
SPList currentList = SPContext.Current.List;
SPWeb currentSite = SPContext.Current.Web;
SPSite currentSiteCollection = SPContext.Current.Site;
SPWebApplication currentWebApplication = SPContext.Current.Site.WebApplication;
*************************************************************************
SPListItem item = (SPListItem)SPContext.Current.Item;
*************************************************************************
SPWeb site = SPContext.Current.Site.OpenWeb(guid);
SPUser user = SPContext.Current.Web.CurrentUser;
*************************************************************************
SPSiteDataQuery siteQuery = new SPSiteDataQuery();
siteQuery.Query = "
"
siteQuery.ViewFields = "
DataTable queryResults = SPContext.Current.Web.GetSiteData(siteQuery);
queryResults.TableName = "queryTable";
queryResults.WriteXml("C:\\queryTable.xml");
The last example makes use of the SPSiteDataQuery object. In WSS V3 there are two different query objects. Besides SPSiteDataQuery object there is also the SPQuery object.
The difference between the two is that SPQuery can only be used for queries within a single folder in a single list. SPSiteDataQuery can be used for cross lists and even cross site queries.
SharePoint Web Services
MOSS 2007 also exposes a series of web services. The MOSS web services allow you to use the Business Data Catalog, document management, Enterprise Search, Excel Services, InfoPath Forms Services, and Web content management (WCM). The table below shows most of the web services, there use and the reference you need to use them.
If you want to use one of the SharePoint web serrvices in your visual studio project you can simply add a Web Reference using the path of the SharePoint site for which you want to use the Web Service and add the web service reference to it. Your reference will then look something like this http://moss/_vti_bin/[webservicereference].asmx.
Uploading a File to a SharePoint Site from a Local Folder
http://msdn.microsoft.com/en-us/library/ms868615.aspx
Thursday, October 2, 2008
Active Directory Change Password
{
if (this.txtNewPassword.Text.Length >= 0)
{
if (this.txtNewPassword.Text.Equals(this.txtConfirmPassword.Text))
{
DirectoryEntry entry;
char[] sep ={ '\\' };
string[] strArray = this.Context.User.Identity.Name.Split(sep);
if (this.isLocalAccount())
{
try
{
// Connect to Active Directory and get the DirectoryEntry object.
// Note, ADPath is an Active Directory path pointing to a user.
entry = new DirectoryEntry("WinNT://" + strArray[0] + "/" + strArray[1], this.Context.User.Identity.Name, this.txtOldPassword.Text, AuthenticationTypes.Secure);
}
catch (Exception exception1)
{
lblMsg.Text = exception1.Message.ToString();
return;
}
try
{
object objectValue = RuntimeHelpers.GetObjectValue(entry.Invoke("ChangePassword", new object[] { this.txtOldPassword.Text, this.txtNewPassword.Text }));
}
catch (Exception exception5)
{
lblMsg.Text = exception5.Message.ToString();
return;
}
}
else
{
try
{
string[] propertiesToLoad = new string[] { "sAMAccountName", "cn" };
DirectorySearcher searcher = new DirectorySearcher("(sAMAccountName=" + strArray[1] + ")", propertiesToLoad);
searcher.SearchRoot.Username = this.Context.User.Identity.Name;
searcher.SearchRoot.Password = this.txtOldPassword.Text;
// You would have created this which searches AD for the specified user
// and returns its DirectoryEntry object or path. See here.
SearchResult result = searcher.FindOne();
if (result == null)
{
lblMsg.Text = "The User was not found in the Active Directory";
}
entry = new DirectoryEntry(result.Path, this.Context.User.Identity.Name, this.txtOldPassword.Text);
// entry.RefreshCache();
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "sAMAccountName=" + strArray[1].ToString(); ;
SearchResult result1 = search.FindOne();
DirectoryEntry user = result1.GetDirectoryEntry();
string NewPassword = this.txtNewPassword.Text;
user.Invoke("SetPassword", new object[] { NewPassword });
lblMsg.Text = "Password has been changed successfully.";
}
catch (Exception exception6)
{
lblMsg.Text = exception6.Message.ToString();
return;
}
}
// lblMsg.Text = lblMsg.Text + this.SuccessMessage;
}
else
{
// lblMsg.Text = lblMsg.Text + this.ErrorMessagePasswordMatch;
}
}
else
{
lblMsg.Text = "Password doesn’t match requirements.";
}
}
Add new element in the web.config file using sharepoint
You can use this code in the feature actived.
try
{
SPWebApplication app = null;
SPWeb web = null;
SPSiteCollection site = properties.Feature.Parent as SPSiteCollection;
if (site == null)
{
web = properties.Feature.Parent as SPWeb;
if (web != null)
app = web.Site.WebApplication;
}
else
app = site.WebApplication;
SPWebConfigModification modification = new SPWebConfigModification();
modification.Name = "add [@Assembly='System.
modification.Path = "configuration/system.web/
modification.Value = @"
modification.Owner = Assembly.GetExecutingAssembly(
modification.Sequence = 0;
modification.Type = SPWebConfigModification.SPWebC
app.WebConfigModifications.
SPFarm.Local.Services.
}
catch (Exception ex)
{
}
The example code could be changed easily to remove the configuration change, as in the following example:
app.WebConfigModifications.Remove(modification);
Add new feature in personal menu
<Feature Id="50E6274F-668C-4f5f-AC85-7DE468957230" Title="My site" Description="My site"
Version="1.0.0.0" Scope="Web" xmlns="http://schemas.microsoft.com/sharepoint/"
ReceiverAssembly="trushar.trushar, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b44e792107d2d835"
ReceiverClass="trushar.trushar.trushar"
>
<ElementManifests>
<ElementManifest Location="elements.xml"/>
</ElementManifests>
</Feature>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<CustomAction Id="PersonalActionsMenu_MyMenu" GroupId="PersonalActions"
Location="Microsoft.SharePoint.StandardMenu" Sequence="101"
Title="My Menu"
Description="My Menu"
ImageUrl="_layouts/images/menuprofile.gif" >
<UrlAction Url="~site/_layouts/test.aspx"/>
</CustomAction>
</Elements>