Thursday, 3 May 2012

SharePoint 2007: How to execute immediatly a custom Timer Job?

One of the most frustrating things in Sharepoint for developers or even administrators, is implementing a new change and then have to wait for the next time in the schedule for the Timer Job to run.

For those who stumble upon this typical MOSS 2007 problem, and wish a particular timer job to execute immediatly:  I created a script that helps me out with it.
Arguments: URL TimerJobname(internal name not the name you see in the CA) ContentDBGuid

Source code:
Program.cs.txt (1.15 KB)

Enjoy!

SharePoint 2007: Property Import Mapping: AD properties cannot be mapped anymore

Once faced with this issue took me quite a while to figure it out. My customer had a recent AD serve rmigration to Windows 2008. Import users was working fine, but when a new property was requested to be mapped, it wa snot available anymore. See image bellow:

Note: The selection of directory service properties may be disabled if the shared service provider is in an untrusted domain or if profile import is not configured.
Note: The selection of directory service properties is disabled because the portal is in an untrusted domain or no irectory service import is configured yet.
Security Note: If you are using a high privilege account to import, you will be able to read and import directory

How was this solved?
1. Going to Shared Services >> User Profiles and Properties >. Configure profile import
2. Click on the link View import Connections
3. Edit the Import Connection
4. Specifiy a domain controller, picked a random controller,
5. Going back to the edit connection and press Auto Discover domain controller.
          
6. problem fixed.... totally random... totally worked!

Enjoy!

SharePoint 2007: Datasheet view not working 0x80070057

I've only found this problem in SharePoint 2010. When creating site columns through a feature, the site column type User can generate Datasheet view errors later on, if you forget to add the property Type="User" in the field description:

<Field ID="{cfede2eb-9f3b-4a6b-8bce-9880d2ea34fc}" SourceID="http://schemas.microsoft.com/sharepoint/v3" Name="FieldUserName" StaticName="FieldUserName" DisplayName="FieldUserName" Group="Field group" BaseType="Text" />

You should have done it like this:

<Field ID="{cfede2eb-9f3b-4a6b-8bce-9880d2ea34fc}" SourceID="http://schemas.microsoft.com/sharepoint/v3" Name="FieldUserName" StaticName="FieldUserName" DisplayName="FieldUserName" Group="Field group" BaseType="Text" Type="User" />

But now that you have deployed it live, the best way so data is not lost, is to correct this programmatically with a script:

static void Main(string[] args) {
string url = args[0];
SPSite site = new SPSite(url);

SPWeb web = site.OpenWeb();

List<SPField> fieldsList = new List<SPField>();

fieldsList.Add( web.Fields[new Guid("{cfede2eb-9f3b-4a6b-8bce-9880d2ea34fc}")] );

//you can add other User type fields where you have forgotten it. 

foreach (SPField field in fieldsList) {

Console.Out.WriteLine("Initial value: " + field.SchemaXml);

if (!field.SchemaXml.Contains("List="))

{

field.SchemaXml = field.SchemaXml.Replace("<Field", "<Field List=\"UserInfo\" ");

field.PushChangesToLists = true;

field.Update();

}
}


Good luck!

SharePoint 2007: Add Metadata to a folder

If you wish to add metadata to a Document library folder it is posible. Just follow through this nice step by step article: http://sharepoint-guru.blogspot.com/2007/06/adding-metadata-to-folder.html

SharePoint 2007: Code blocks are not allowed in this file

After editing a masterpage, or page layout you get the following error:

"An error occurred during the processing of /_catalogs/masterpage/masterpagename.master. Code blocks are not allowed in this file. "




Solution:


1. open the web.config add the following code in <sharepoint> <safemode..>:

<SharePoint>
<SafeMode MaxControls="200" CallStack="false" DirectFileDependencies="10" TotalFileDependencies="50" AllowPageLevelTrace="false">
<PageParserPaths>
<PageParserPath VirtualPath="/*" CompilationMode="Always" AllowServerSideScript="true" IncludeSubFolders="true" />
</PageParserPaths>
</SafeMode>

....

2. Add the following safecontrol:

<SafeControl Src="~/_catalogs/masterpage/*" IncludeSubFolders="True" Safe="True" AllowRemoteDesigner="True" />


Good luck! :)

SharePoint 2007: Change the port for the Central Administration

This is piece of cake! Just apply the following command:

Stsadm –o setadminport –port 99999

This command will change SharePoint Central Administration v3 to run on port 9999. No need for IISRESET or reboot. Enjoy!

SharePoint 2007: The user doe snot exist or is not unique

When adding a user to a group, if it happens to get the error "The User does not exist or is not unique", can happen due to many reasons and usually after migrating a Portal. But if consistently happens to many different users. Try this!



1. check the following property:

stsadm -o getsiteuseraccountdirectorypath -url http://www.moss.com

2. if it returns something like:

<SiteUserAccountDirectoryPath>ou=team,ou=department,ou=company,

DC=domain,DC=com</SiteUserAccountDirectoryPath>

3. Try applying:

stsadm -o setsiteuseraccountdirectorypath -url http://www.site.com -path ""

Operation completed successfully.



This worked for me! Good luck!



reference: http://www.msexperts.org/blogs/mark/archive/2009/10/28/the-user-does-not-exist-or-is-not-unique.aspx

SharePoint 2007: "The extension .mdb may be incorrect" How to use .mdb files?

Some customers might like to use Access files as they use Excel & Word files. But the *.mdb files are blocked by default.

You must unlock/unblock these files in different places: SharePoint Central Admin, IIS & eventually the .NET web.config file.



1. Go to Central Administration > Operations > Blocked file types

2. In a page like the image below, remove the mdb file & press OK



3. Now you can upload MDb files.

4. The problem with MDB files is that you cannot download them later on by default.

5. When trying to click of save target as in an uploaded file, you might get the following error:

the type of page you have requested is not served because it has been explicitly forbidden. The extension .mdb may be incorrect.Please review the URL below and make sure that it spelled correctly.




6. Despite the fact some articles might recommend you to:

6.1 Open IIS

6.2 Go to Properties of the website (Root) > tab Home Directory > Button Configuration

6.2 Now remove the following 'ISAPI' extensions map entry: ".mdb"

6.3. This is sometimes NOT ENOUGH!

7. Change the AS.NET web.config file:

7.1 C:\WINDOWS\Microsoft.NET\Framework\VERSION\CONFIG

7.2 Open the Web.config file, and comment the following line in the image:

<add path="*.mdb" verb="*" type="System.Web.HttpForbiddenHandler" validate="true"/>




7.3 Don't do this, if your application is using an mdb file that can end up being downloaded and therefore leaking your DB info...

Good luck!

SharePoint 2007: Multiple Upload Not working (or not available)

Sometimes SharePoint users notice that Multiple Upload is not available when trying to upload documents. This usually has to do with their company security settings.

The following conditions are needed to have Multiple Upload working:

1. At least Office 2003 must be installed.
2. Enable the ActiveX controls:
   2.1 Go to Internet Explorer > Tools > Internet Options > Security Tab
   2.2 Here in the "custom level' button activate/enable the Active X controls that say "Script ActiveX controls maked safefor scripting*", like in the image below:



You can also check the following:

1. Check that the Windows SharePoint Services Support component (under 'Office Tools') has been installed by the Office setup program. This installs an ActiveX control that provides functionality such as support for uploading multiple documents within IE. If it does show as installed use the Repair option so that Office setup can ensure it is installed correctly.

2. You can check if the upload ActiveX control is installed correctly by going to Manage Add-Ons in IE8 (or 7). Set the filter to show 'All Add-Ons'. Under Toolbars and Extensions look for the STSUpld UploadCtl Class and ensure it is enabled. It should have a major version of 12, for example 12.0.4518.1014 > not sure if it is this version without Office 12.

Good Luck!

SharePoint 2007: Editing a document that Opens as Read Only

When you are trying to edit your Office documents, in SharePoint, they always open with [Read-Only]?

This issue has a lot of articles online with several suggestions. Here's some:

1. A solution I found for one of my customers (IE6 & Office2003):
   1. Open Windows Explorer (not the browser! Can be by opening any folder)
   2. Go to the menu “Tools”
   3. Select “Folder Options…”
   4. Open the tab “File Types”, and it will list a big list of file types
   5. Select the Excel File type (XLS)
   6. Click on the button “Advanced”
   7. In this new window uncheck the option “confirm open after download” (image below)


2. Microsoft Article: http://support.microsoft.com/?kbid=870853 >> not pratical when you have a few hundreds of users in the portal
  • Quit all running Office 2003 programs.
  • Open register (regedit.exe)
  • Locate and then right-click the following registry subkey: HKEY_CURRENT_USER\Software\Microsoft\Office\11.0\Common\Internet
  • Point to New, and then click DWORD Value.
  • Type OpenDocumentsReadWriteWhileBrowsing, and then press ENTER.
  • Right-click OpenDocumentsReadWriteWhileBrowsing, and then click Modify.
  • In the Value data box, type 1, and then click OK.
  • On the File menu, click Exit to quit Registry Editor.

3. Another approach: MSDAURL.DLL rights

http://blogs.technet.com/anneste/archive/2009/01/28/editing-a-document-in-sharepoint-opens-as-read-only.aspx

4. But, what if you are working in large corporation and you can not so easy push this registry change to all machines?
  • This article contains an interesting approach, and involves adding a new JavaScript file: http://dotnetninja.wordpress.com/2009/01/12/how-to-open-sharepoint-documents-in-edit-mode-with-internet-explorer-6-and-windows-xp-without-regfix/

Wednesday, 2 May 2012

SharePoint 2007: Profile import stuck, search crawl stuck & audiences do not compile

If you notice in SharedServices that:

1. the profile import is enumerating the same number (marked in yellow in the image below), the stop import is non responsive.



2. The search is crawlling for too long, gets stuck in the status "stopping" if you try to stop.

3. Your audiences are not compiling, because the import has not finished (mage below).





These are several syntoms that the service "Office SharePoint Server Search" is not working properly.

How to solve this?

1. In Windows, go to Administration Tools > Services

2. STOPthe service "Office SharePoint Server Search".

3. If step 2 fails, open the Windows Task Manager and kill the proccess "mssearch.exe"

4. Perform IISRESET

5. Go to Administration Tools > Services, and START the service "Office SharePoint Server Search".

6. Go to Share Point Central Administration > Shared Services

7. Open the User Profiles and Properties page, and verify if it is importing proper now.





Xtra suggestions:

Reset Search Index:

Now that (hopefully) everything is working fine, we should be concerned about the cause of this issue. Quite likely the search crawll got stuck at some point, and could be the cause for all this trouble. The best is to reset the current Search Index, and rebuilt it.

1. Go to Central Admin > Shared Services > Search Administration

2. Click on "Reset all crawlled content"

3. Go to "Content Sources" start manually a full crawll on the nedded content sources.


Good luck!

SharePoint 2007: Save site as template missing?

The link "Save site as template" is only available under Look and Feel at the Top Level of the site collection.
If you are trying to save a site as a template in WSS v3 or MOSS 2007 you need to append _layouts/savetmpl.aspx to your sub sites url.

1. Supposing your subsite is:

    http://portal.moss2007.com/subsite/default.aspx

2. You should go to:

     http://portal.moss2007.com/subsite/_layouts/savetmpl.aspx

and then you would be able to save the site as a template.

Note: there might be cases where this will not work.

Good luck!

SharePoint 2007: How to display blog post archives

Most blog engines allow you to display a list of blog posts grouped by month. Unfortunately SharePoint blog sites do not give you that ability, out of the box.

Here is a simple solution (no codding required) on how to overcome that limitation:

Download webpart

Read the original article…

SharePoint 2007: List does not exist OR Invalid SPListItem. The SPListItem provided is not compatible with a Publishing Page

Are you see ing this error when you try to create a new page in a SharePoint site?

" List does not exist The page you selected contains a list that does not exist. "

Or are you also seeing this error when you try topen one of your pages?

"Invalid SPListItem. The SPListItem provided is not compatible with a Publishing Page."



Here is my non-sense solution (found after long trial and error an looking online):

1. Go to the Pages library where the file is stored

2. Create a new page, but from a different type than the pages that are failing

3. In the New Page area, select the page layout that is failing and create a test page

4. Your page is created successfully… and now you can see your pages…

A lot of trial & error… made me find this… seems a SharePoint… and not the access denied error & manage schedule errors I found before.



Good Luck!



My related search sources that helped my find this fabulous non-sense solution;

http://www.eggheadcafe.com/community/aspnet/69/10072753/list-does-not-exist-error.aspx

http://vspug.com/camper/2007/08/27/list-does-not-exist-error-message-1-cause/

SharePoint 2007: Workflows deployment issues

Are you going nuts after deploying your workflows & several IISRESETs and you see that it still behaves the same???


If your changes were on the designer editor (for instance changing a method for a if branch condition). After deploying your solution (or manually copying your DLL to the GAC) you need:


1. Remove the workflow from the list that uses it
2. Deactivate the Feature of the workflow
3. Reactivate the feature.
4. Re-attach the workflow to the list.

SharePoint 2007: Paging Content Query Web Part

Recently came accros with the request for paging in a Content Query WebPart, because reinveing the wheel is a waiste of time. I ended bumping into this interesting webpart: Enhanced Content Query Web Part.

I ended up needing to customize some code, change the Pager webpart XSL and apply some CSS as well. But Worked beautifully after deployed & implemented.

If you want to read more general information; http://blog.mastykarz.nl/paging-content-query-web-part/.
Good luck!

SharePoint 2007: tag Cloud Web Part

Bamboo launched, already sometime ago a Tag Cloud Web Part. You can find more info at: http://community.bamboosolutions.com/blogs/bambooteamblog/archive/2009/04/15/sharepoint-tag-cloud-web-part-just-released-to-bamboo-labs.aspx
You can download it for free at:
http://community.bamboosolutions.com/media/p/17525.aspx

SharePoint 2007: Automatic user profile removal (My Site Clean up Job)

In SharePoint 2007 the inactive user profiles are deleted by a timer job called “My Site Cleanup Job” (Central Administration > Operations > TimerJobs Definitions > My Site Cleanup Job").


It is NOT after the third consecutive failed import that the automatic profile deletion happens.
So if your profiles are still appearing after import check the following:
1. Is your LDAP filter importing disable profiles?
    The LDAP filter must be something like to avoid importing disabled profiles:
    (&(objectCategory=person)(objectClass=user)( !(userAccountControl:1.2.840.113556.1.4.803:=2)))
    check this article: http://support.microsoft.com/kb/827754

2. Is your "My Site Cleanup" timer job enable? (see above)
   Central Administration > Operations > TimerJobs Definitions > My Site Cleanup Job").
   Enable it!
3. Is "Windows SharePoint Services Timer " service running?
   Administrative Tools > Services > Windows SharePoint Services Timer 
   Start it!

SharePoint 2007: Workflow notifications not being sent to user/sapprover

This issue can happen for many reasons:

1. The Email server is down, or the server is not allowing your SharePoint server to send emails. Check each SharePoint Server in the farm individually.

2. Check if your Windows SharePoint Services Timer service is running. To start it go to my article:
   http://duartenobrega.blogspot.com/2012/05/sharepoint-2007-timer-jobs-not-working.html

If these don't help, let me know what was your problem & solution in the comments below! :)

SharePoint 2007: How to delete SharePoint Timer Job Definition

If you would like to delete Sharepoint Timer Job Definitions follow these steps:

1. Go to Central Administration > Operations

2. Click on Timer Job Definitions

3. In this page go to the job that you wish to delete

4. Copy the GUID shown in the URL field of the browser (something like below:

    http://centraladmin.company.com/_admin/JobEdit.aspx?JobId=99346da8%2D1cba%2D4691%2D8c18%2D4e257650aa72

5. Copy to NotePad and replace the %2D characters by a dash "-"

5. Then go stsadm and run the following command:

     stsadm.exe -o deleteconfigurationobject -id <ObjectGUID>

The command stsadm.exe -o deletessptimerjob is for deleting Shared Services timer jobs. Which rarely is needed...



Good luck!

Event ID: 6398 6482 7076 SharePoint memory is corrupt

Event ID: 6398 6482 7076 Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Check the following article & install the hot fix: http://support.microsoft.com/kb/946517/en-us

This occurs in IIS when more than 2 AD users try to access the same proccess.

SharePoint: 2007How to import profile information of enabled user accounts

If SharePoint is importing disabled profiles, you should change the profile import filter.
1. Go to Shared Services >User Profiles and properties
2. Click on Configure Profile Import
3. In the Source area, click on "View import connections"
4. Edit your Active Directory connection
6. In the "User filter" field, paste the following string: (&(objectCategory=person)(objectClass=user)( !(userAccountControl:1.2.840.113556.1.4.803:=2))), see image below:

7. Click OK.


Microsoft article: http://support.microsoft.com/kb/827754

SharePoint 2007: Increase the maximum upload limit on SharePoint web application

Increasing the maximum upload limit for a SharePoint site collection can be configured on the Central Administration. But sometimes it is not enough, you might need to increase some time out configurations.
So you must consider:
   1. Configure in Central Administration
   2. Configure Time outs:
      2.1 IIS  
      2.2 Web.config

1. Configure in Central Administration
   1. Open the Central Administration>
   2. Go to "Application Management" , then ""Web Application General Settings"
   3. Make sure you selected the correct web application and modify the "Maximum Upload Size" field.

2. Time Outs
   2.1  IIS
         1. Open IIS, select the website and open its properties. 
       2. Open the "Web Site" tab. Set the value in "Connection timeout" field (see image below).
       3. You should consider 120 seconds per extra 50MB upload.


   2.2 Web.config
         1. Edit C:\Program Files\Common Files\Microsoft Shared\Web server extensions\12\TEMPLATE\LAYOUTS\web.config
               1.1 add or change the following "ExecutionTimeout" property to the value shown:


         2. Edit the web.config of your Web application.
                2.1 add or change the following "ExecutionTimeout" property to the value shown:

SharePoint 2007: LDAP filters & Profiles Import

I posted an article about how to prevent importing disable AD accounts. But sometimes you can make good use of LDAP filters toa void importing service accounts for instance, and other filters according to your needs:

Example LDAP User Filters

Default user filter:
(&(objectCategory=Person)(objectClass=User))

Exclude accounts with no email address:
(&(objectCategory=Person)(objectClass=User)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(mail=*))

Exclude disabled accounts:
(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))

Exclude accounts with passwords set to expire:
(&(objectCategory=person)(objectClass=user)(!userAccountControl=65536))

Include only the accounts with valid email addresses
(&(objectCategory=Person)(objectClass=User)(mail=*com)

Include only the accounts that are part of the Branch1 organizational unit
(&(objectCategory=Person)(objectClass=User)(memberof:1.2.840.113556.1.4.1941:=(CN=Authenticated Users,OU=Branch1,DC=domain,DC=local)))

Exclude accounts that don’t have a first name
(&(objectCategory=Person)(objectClass=User)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(!(!givenName=*)))

Useful links:
1.LDAP Filter syntax: http://msdn.microsoft.com/en-us/library/aa746475(VS.85).aspx
2.LDAP Query Basics: http://technet.microsoft.com/en-us/library/aa996205(EXCHG.65).aspx
3.LDAP ADModify tool (can be useful to test queries): http://admodify.codeplex.com/

SharePoint 2007: Faceted Search fills//clogs Event Viewer?

Faceted Search once implemented in SharePoint with the default settings, logs every search query a user performs and issues an Access Denied error too (WindowsIdentity:domain\user; Message Cannot open log for source 'Enterprise Library Data', you may not have write access). In an environment with a few thousand users, performing several search queries, your Event Viewer will clog in a short time.
Usually you find this issue when you get the following error page:
[InvalidOperationException: Cannot open log for source 'Enterprise Library ExceptionHandling'. You may not have write access]

And you might notice other syntoms like: target audiences not working well, search not working.

Suggestions:

1. BEST: turn off the Faceted Search Logging

2. Increase the Event Viewer log file size.

3. Decresease the days of an event expiration.


Turn Off the Faceted Search Logging:

1. Go to the web.config of all your sharepoint web application in all farm servers

2. Set the following filter property to Off:
<add source="Faceted Search Logging" formatter="Text Formatter" log="Application" machineName="" listenerDataType="Microsoft.Practices..." traceOutputOptions="None" filter="All" Type="Microsoft.Practices.EnterpriseLibrary.Logging...." name="Formatted EventLog TraceListener" />

SharePoint 2007: Workflow History lost?

Recently I had a customer complaining that after a period of time their approval workflows history was disappearing. By Default SharePoint removes any workflow history and tasks after 60 days period.

So I created a script that increases the AutoCleanupDays of the SPWorkflowAssociation through the whole site collection (given as paramenter for the command script). The code sample below increases all Worflow associations expiration to 99999 days, which is more than enough to keep track of your documents history approval.

If you wish you can recycle the code as a timer job.

Code sample:
using (SPSite sitecollection = new SPSite(http://mossdev))
{
using(SPWeb site = sitecollection.OpenWeb()){
   SPWorkflowAssociation _assoc = null;
   SPList list = site.Lists["Shared documents"];
  foreach (SPWorkflowAssociation assoc in  list.WorkflowAssociations)
   {
        _assoc = assoc;
        _assoc.AutoCleanupDays = 99999;                        
   }
   list.UpdateWorkflowAssociation(_assoc);
   list.Update();
   }                
 }

This code increases the expiration period of a workflow history to 99999 days, 
for all Workflow associations in the opened web object.
It saves an HTML file in the root Documents library with a log of the changes 
performed, with a date stamp.

Script & Code source files:
WorkFlow_AutoCleanUpConfigScript.zip (3.45 KB)
WorkFlow_AutoCleanUpConfigSource.zip (802.16 KB)

SharePoint 2007: SPListItem.URL returns invalid URL?

SPListItem.Url returns an invalid URL?

something like: http://mossdev/Lists/ThisList/155_.000 ?

The way to is instead of using the following code:

listItem.Url

Here goes two suggestions

1. listItem.ParentList.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url + "?ID=" + listItem.ID

If this returns something like: http://mossdev/Pages/Lists/ThisList/DispForm.aspx?ID=155

This means you are using a relative URL. Build an absolute:


2. listItem.Web.Url + "/" + listItem.ParentList.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url + "?ID=" + listItem.ID

SharePoint 2007 & SQL Server: Search DB is too large after Reset all crawlled content

Sometimes the Indexing generates an unsual big size mdf file for the search database. If you have disk space shortage this article might help you.
Once you reset the all cralled content in the Shared Services > Search Settings, if the Search DB is too large and you have disk space issue sin your DB server you must do the following:
1. Go to Shared Services > Search
2. Go to Content Sources and crawll schedules.
3. Stop all search crawls.
   Note: Stopping the search crawlls usually generates big LOG files that can clog your DB server if it is already struggling with lack of space.
4. Reset all crawlled content (Shared Services > Search Settings)
3. Go to the DB server and open SQL 2005.
4. Now the search DB must be shrunk:
5. Right click the search DB go to All Tasks > Shrink > Database, follow the image below (you must check "reorganize files..."):


6. Right click the search DB go to All Tasks > Shrink > Files, with default settings:


7. This should be enough to release space from your DB server. Good luck! :)

SharePoint 2007: Birthday web part "datenoyear" issues

We built a Birthday webpart that returns the first x birthdays starting today.
The Birthday profile field, is type "datenoyear". What I noticed is that this field includes the year that you fill in the birthday date. For instance for "18 January" it will fill in 1/18/2009.

The problems lays on birthdays that the users inserted back in 2007 & 2008. Their birthdays are queried according to the query below:
            query.Append(birthdayField);
            query.Append("\" >= GETGMTDATE() ) ");
            query.Append("ORDER BY \"");
            query.Append(birthdayField);
            query.Append( "\"</QueryText>" );

Because some functions like MONTH() or DAY(), do not work in MOSS FullTextSqlQuery, one of the ways to get around this was creating a scheduled task that updates birthdays every week, before a full indexing crawll happens.

This script was developed by a colleague at TamTam (Peter Geritsen), I added code, to update to the following year birthdays previously to the current day, so that in the last months of a year shows birthdays of the following year.

CODE (posible to download, see BrithdayReset_SourceCode.zip file in this post):

...
UserProfileManager profileManager = new UserProfileManager(context);
                    IEnumerator profileEnumerator = profileManager.GetEnumerator();
                    int countUpdated = 0;
                    while (profileEnumerator.MoveNext())
                    {
                        UserProfile profile = profileEnumerator.Current as UserProfile;

                        if (profile[birthdayFieldName].Count != 0)
                        {
                            DateTime birthday = (DateTime)profile[birthdayFieldName].Value;

                            //if (birthday <= DateTime.Now.AddDays(-1))
                            int yearDiff = DateTime.Now.Year - birthday.Year;
                            if (yearDiff != 0)
                            {
                                // set year to this year
                                birthday = birthday.AddYears(yearDiff);
                                profile[birthdayFieldName].Value = birthday;
                                Console.WriteLine("Birthday of {0} changed to: {1}", profile["PreferredName"].Value, birthday.ToShortDateString() + " : " + birthday.ToString());
                                countUpdated++;
                            }

                            //if the birthday has already been, must update it to the following year.
                            //This prevents from birthdays of the following next year by the last weeks of the year not showing.
                            if(DateTime.Compare(birthday, DateTime.Now)<0)
                            {
                                birthday = birthday.AddYears(1);
                                profile[birthdayFieldName].Value = birthday;
                                Console.WriteLine("Birthday of {0} changed to: {1}", profile["PreferredName"].Value, birthday.ToShortDateString() + " : " + birthday.ToString());
                                countUpdated++;
                            }

                            profile.Commit();   
                        }
                    }

...

Run the script:
BirthdayReset fieldName PortalURL
You can make it a scheduled task in Control Panel to happen periodically

NOTE:
Architecturaly it is more "elegant" to create a TimerJob that will run this code periodically.

Download Source Code:
BirthdayReset_SourceCode.zip (1.3 MB)


SharePoint 2007: using SPSecurity.RunWithElevatedPriviledges but still prompt's a Windows login

When your sharepoint portal or internet site prompts windows logins, there can be many reasons but a very typical is that some webpart is trying to access information to which is not authorized.
Using SPSecurity.RunWithElevatedPrivileges, prevents this, but this must be used wisely.

1. SPSecurity.RunWithElevatedPrivileges & opening sites
The following code sample will prompt a login windows for some users:
Example 1:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
      SPSite thisSite = SPContext.Current.Site;
      SPWeb thisWeb = thisSite.OpenWeb();
}

One should not use SPContext.Current.Site within RunWithElevatedPrivileges the because this will run under the current user, and not with the high rights account.

So the code on Example 1, should be as bellow:

Example 2:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
      SPSite thisSite = new SPSite(SPContext.Current.Site.Url);
      SPWeb thisWeb = thisSite.OpenWeb();
}

Opening the Site with new SPSite(SPContext.Current.Site.Url); will use the Admin account, and not the current user.


2.  SPSecurity.RunWithElevatedPrivileges & opening list items
The same problem when using lists.

Example 3:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
    SPSite thisSite = new SPSite(SPContext.Current.Site.Url);
    SPWeb thisWeb = thisSite.OpenWeb();
    SPListItem li = SPContext.Current.ListItem;
    PublishingPage page = PublishingPage.GetPublishingPage(li);
}


This might prompt a login window for some users,  using  SPContext.Current.ListItem within RunWithElevatedPrivileges will run under the current user, and not with the high rights account.
So the code on Example 3, should be as bellow:

Example 4:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
    SPSite thisSite = new SPSite(SPContext.Current.Site.Url);
    SPWeb thisWeb = thisSite.OpenWeb();
    SPListItem li = web.Lists[SPContext.Current.List.ID].Items[SPContext.Current.ListItem.ID];
    PublishingPage page = PublishingPage.GetPublishingPage(li);
}


Opening the list item with web.Lists[SPContext.Current.List.ID].Items[SPContext.Current.ListItem.ID]; will use the Admin account, and not the current user.

SharePoint 2007: How to verify if a user is a Site Administrator

In many Sharepoint projects the following code has been user to check if a certain user has full control or not over a specific site:
if (!SPContext.Current.Web.CurrentUser.IsSiteAdmin)

But this code only check if a user is a Site Collection administrator. Even if the current user is in the owners group, it will not work. And therefore, problems will happen once implemented live.

Workaround:
I wrote a method that checks if a user belongs to the Owners group:
f(!isCurrentUserOwner())

Method:
private bool isCurrentUserOwner()
        {
            bool currentUserOwner = false;

            SPUser currentUser = SPContext.Current.Web.CurrentUser;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    SPSite currentSite = new SPSite(SPContext.Current.Site.Url);
                    SPWeb currentWeb = currentSite.OpenWeb(SPContext.Current.Web.ID);
                    SPGroup ownersGroup = currentWeb.AssociatedOwnerGroup;

                    //Check if currentuser belongs to owners group of the current web
                    foreach(SPUser user in ownersGroup.Users)
                    {
                        if (currentUser.ID == user.ID)
                        {
                            currentUserOwner = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    //blah blah
                }             
            });

            //Not an owner member
            return currentUserOwner;
        }


SharePoint 2007: Timer jobs not working?

Is your Sharepoint Portal suffering from any of the following symptoms?
- Scheduled Audience compilation is not happening anymore?
- Scheduled Index crawll is not happening anymore?
- Scheduled Profile Import is not happening anymore?
- Users Memberships or My Settings properties are not updated anymore?

Clearing the file system cache on all servers in the server farm on which the Windows SharePoint Services Timer service is running.

To solve this, follow these steps:
1. Stop the Timer service. To do this, follow these steps:
2. Click Start, point to Administrative Tools, and then click Services.
3. Right-click Windows SharePoint Services Timer, and then click Stop.
4. Clear the cache. To do this, follow these steps:
    4.1. Open the following folder: %ALLUSERSPROFILE% \Application data\Microsoft\SharePoint\Config\<GUID>
    4.2. Open the cache.ini file and change the value to 1. Save the change and close the cache.ini file.
    4.3. Delete or move all of the XML files.
5. Start the Timer service. To do this, follow these steps:
6. Click Start, point to Administrative Tools, and then click Services.
7. Right-click Windows SharePoint Services Timer, and then click Start.