HttpModules

on Monday, September 21, 2009

HttpModules sit in the ASP.NET processing pipeline and can listen for events during the processing lifecycle. Modules are good solutions when the behavior you want to achieve is orthogonal to the page processing. For instance, authentication, authorization, session state, and profiles are all implemented as HttpModules by the ASP.NET runtime. You can plug-in and remove these modules to add or discard their functionality. Here is a module to set the MasterPageFile property on every Page object.


using System;
using System.Web;
using System.Web.UI;

public class MasterPageModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
}

void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
Page page = HttpContext.Current.CurrentHandler as Page;
if (page != null)
{
page.PreInit +=new EventHandler(page_PreInit);
}
}

void page_PreInit(object sender, EventArgs e)
{
Page page = sender as Page;
if (page != null)
{
page.MasterPageFile = "~/Master1.master";
}
}

public void Dispose()
{
}
}

Good Sharepoint Articles

on Wednesday, September 2, 2009

http://sheltonblog.com/category/1.aspx?Show=All

Sharepoint Event receivers

on Saturday, August 29, 2009

Example 1:Updating Item properties

Imp Note: See the use of EnableEventFiring() and DisableEventFiring() methods in ItemUpdated event to prvent infinite loop of event firing.
public class CustomListItemReceiver:SPItemEventReceiver
{
public override void ItemAdded(SPItemEventProperties properties)
{
try
{
File.AppendAllText(@"c:\abc.txt", properties.ListTitle);
}
catch (Exception exception)
{
throw;
}
}

public override void ItemDeleting(SPItemEventProperties properties)
{
base.ItemDeleting(properties);
}

public override void ItemUpdated(SPItemEventProperties properties)
{
DisableEventFiring();
properties.ListItem["Nickname"] = properties.ListItem["Nickname"] + "hello";
properties.ListItem.Update();
EnableEventFiring();
File.AppendAllText(@"c:\abc.txt", properties.ListTitle);
}

Example 2: Invoke SPD workflow from event receivers

public class InvokeWorkflow : SPItemEventReceiver
{
public override void ItemAdded(SPItemEventProperties properties)
{
SPListItem currentItem = properties.ListItem;
SPWorkflowManager manager = currentItem.Web.Site.WorkflowManager;
foreach (SPWorkflowAssociation association in currentItem.ParentList.WorkflowAssociations)
{

manager.StartWorkflow(properties.ListItem, association,"", false);
}
}
}

Event Registration>


Method 1:Using Object Model to attach receiver to specific doc lib

using (SPSite site = new SPSite("http://localhost:1982/"))
{
using (SPWeb web = site.OpenWeb())
{
//File.AppendAllText("c:\\abc.txt", "hello");
SPList list = web.Lists["Leave Applications"];
foreach (SPEventReceiverDefinition def in list.EventReceivers)
{
//if(def.Class.Contains("ListItemEvent"))
//def.Delete();
Console.WriteLine(def.Name + def.Type.ToString() + def.Class);
}
list.EventReceivers.Add(SPEventReceiverType.ItemAdded, "FormLibraryEventListener, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1f46df2818ed96ab", "FormLibraryEventListener.InvokeWorkflow");
list.EventReceivers.Add(SPEventReceiverType.ItemUpdated, "FormLibraryEventListener, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1f46df2818ed96ab", "FormLibraryEventListener.InvokeWorkflow");
}
}

Method 2:Using Features to attach receiver to specific Template doclibs

Feature.xml file content
<?xml version="1.0" encoding="utf-8" ?>
<Feature xmlns="http://schemas.microsoft.com/sharepoint/" Id="1E90FEC8-0301-4e77-A261-2907FF5BDECF"
         Title="Invoke Workflow Event Receiver" Scope="Web">
  <ElementManifests>
    <ElementManifest Location ="elements.xml" />
  </ElementManifests>
</Feature> 
elements.xml file content
<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Receivers ListTemplateId ="115">
    <Receiver>
      <Name>MyListItemEventReceiver</Name>
      <Type>ItemAdded</Type>
      <SequenceNumber>10000</SequenceNumber>
      <Assembly>FormLibraryEventListener, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1f46df2818ed96ab</Assembly>
      <Class>FormLibraryEventListener.InvokeWorkflow</Class>
    </Receiver>
    <Receiver>
      <Name>MyListItemEventReceiver</Name>
      <Type>ItemUpdated</Type>
      <SequenceNumber>10000</SequenceNumber>
      <Assembly>FormLibraryEventListener, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1f46df2818ed96ab</Assembly>
      <Class>FormLibraryEventListener.InvokeWorkflow</Class>
    </Receiver>

  </Receivers>
</Elements>






Get and Delete all the database of sql server


DECLARE @SQLString VARCHAR(MAX) = ''

Select @SQLString = @SQLString + 'ALTER DATABASE ' + QUOTENAME(name) + ' SET SINGLE_USER WITH ROLLBACK IMMEDIATE;DROP DATABASE ' + QUOTEName(name) + ';'
FROM sys.databases
WHERE name NOT IN ('master','model','msdb','tempdb')
OR is_distributor = 0x1

EXEC(@SQLString)

Add Farm Administrator using stsadm

on Friday, August 28, 2009

Don’t know how, don’t know when (Vera Lynn), but one day we lost access to our SharePoint Central Administration. The reason of this was that someone deleted the BUILTIN\Administrators from the Farm Administrators group.

No problem, just add the BUILTIN\Administrators back to the Farm Administrators Group.

But how do you do this without access to the Central Administration?

Well, after some searching and googling I found a solution. You can use STSADM to add people to groups in a Site Collection and the Central Administration is just another Site Collection.

I know the suspense is killing you so here ’s the STSADM command:
stsadm -o adduser -url http://server:12345 -userlogin BUILTIN\Administrators -useremail admin@company.com -group “Farm Administrators” -username “Administrators”

SPListTemplateType programmatically

on Tuesday, August 25, 2009

Code to List TemplateTypes

string[] typeNames = System.Enum.GetNames(typeof(SPListTemplateType));
Array typeValues = System.Enum.GetValues(typeof(SPListTemplateType));

int j = 0;

foreach (int i in typeValues)
{
Console.WriteLine(typeNames[j++].ToString() + " " + i.ToString ());
}

The output of the codesnippet above should look something like this:

GenericList 100
DocumentLibrary 101
Survey 102
Links 103
Announcements 104
Contacts 105
Events 106
Tasks 107
DiscussionBoard 108
PictureLibrary 109

SPWebApplication.Delete – Deletes Web Application – Myth Busted!!

on Monday, August 24, 2009

If someone asks you, how to delete a WebApplication from the code API, the simple answer is to use – SPWebApplication.Delete(). So logically, you would expects that when you run this command it would remove the web application from central admin (Config DB) and also remove the associated contents – Content DB and IIS WeB Application, App Pool and the home directory. (That’s the myth I am talking about)

But on close analysis found that this command only removes the Web application from the config db but rest of the associated resources remain behind (as zombies – Can’t be used). To completely delete the associated resources you need to explicitly call the commands for deleting the content DB and the IIS resources.

On research I found the sample code below works perfectly.

1: SPWebApplication wa = SPWebApplication.Lookup(new Uri(""));
2:
3: SPContentDatabaseCollection dbColl = wa.ContentDatabases;
4: foreach (SPContentDatabase db in dbColl)
5: {
6: db.Unprovision();
7: }
8:
9: wa.Delete();
10: wa.Unprovision();
The code SPContentDataBase.UnProvision() deletes the content dbs and the command SPWebApplication.UnProvision() deletes the IIS web site, app pool and the root folder.

The reason why this was missed in the command SPWebApplication.Delete(), I guess was to give you more granularity and power to control different actions.