Skip to main content
Malcan Logo

Polski  English  
  
Malcan > Articles > Tips and tricks  

Tips and tricks

Dear Guest, this page is collecting some useful practices and small examples of information/code - just to to be useful for the community. If you want to change anything drop me your suggestions here, please. I will be grateful if you add link to this page on your site or other forum if it is appropriate.

   
Last modified at 11/28/2009 20:20  by Artur Malinowski 

Edit
Sort by AttachmentsUse SHIFT+ENTER to open the menu (new window).
HintFilter
Expand/Collapse Technology : .Net ‎(5)
 .NET Runtime 2.0 Error Reporting, Event ID 5000 - Cannot see exception details in Windows Log
Sometimes you are facing errors in Windows event log that don't present all the details e.g. from your own .Net application.
 
The reason for that is your application cannot log events without registered log source. You have two options to solve it:
 
1) Run you code once as local administrator (once) - having more permissions Windows will automatically create good source for you. Then you may run the code without administrative permissions (source is already registered)
 
2) Create the source for event as an administrator. Add one using REGEDIT under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\
underneath there should be EventMessageFile key of type REG_EXPAND_SZ with value c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll
 
The example in VB.Net for your all application should look like:
 
Imports System.Diagnostics
 
    Const LogSource As String = "TestException"
    Sub Main()
        Try
            Throw New Exception("I cannot do something")
        Catch ex As Exception
            EventLog.WriteEntry(LogSource, ex.ToString)
        End Try
    End Sub
 Extracting server name, relative path, parameters having URI or URL
It is usual need to play with different portions of URL. Here are useful examples how to extract particular items:
 
Uri oUrl = new Uri("http://malcan.com:23/site/file.txt?p1=a&p2=b", UriKind.Absolute)
 
oUrl.Scheme      : "http"
oUrl.Authority   : "malcan.com:23"
oUrl.AbsolutePath: "/site/file.txt"
oUrl.Query       : "?p1=a&p2=b"
 Reading/Writing to AppKey, Web Configuration

In Web.Config in the section <configuration> you need to have the following:
 <appSettings>
    <add key="AppKey" value="AppValue"/>
 </appSettings>

and then may read/write using this
System.Configuration.ConfigurationManager.AppSettings("AppKey")

Remember also to reference System.Configuration first.

==> You may also reference your app settings putting them in separated file. Then firstly you add a reference with file attribute, and second paragraph represents your additional file (saved as UTF8). Both keys are merged into one (both keys are valid). It is also nice that IIS does not "reset" whenever additional file is changed.

 <appSettings file="myFile.config>
    <add key="KeyInWebConfig" value="Value1"/>
 </appSettings>

 <?xml version="1.0" encoding="utf-8" ?>
 <appSettings>
    <add key="KeyInSeparatedFile" value="Value2"/>
 </appSettings>

 Trace to file without changing the code
.Net example of code doing tracing:
Private Sub testMethod()
    Trace.Indent()
    Trace.WriteLine("Start: testMethod")
End Sub

Example of configuration file for standalone (exe):
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
 <system.diagnostics>
  <trace autoflush="true" indentsize="2">
   <listeners>
    <remove name="Default"/>
    <add name="FileLogListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="FileLogListener.txt"/>
   </listeners>
  </trace>
 </system.diagnostics>
</configuration>

 Windows Authentication
The user accessing web server that is Windows authenticated on IIS Server (Windows Integrated Authentication):
System.Web.HttpContext.Current.User.Identity.Name()
 
The user context that is running the service (windows application or IIS Application Pool in IIS):
System.Security.Principal.WindowsIdentity.GetCurrent().Name()
Expand/Collapse Technology : ASP.Net ‎(1)
 Could not load type ... when using your web control ASCX or web page ASPX
When trying to use your user control that was created in the Web Application Visual Studio project you face the error message "Could not load type" with your assembly name. In Sharepoint you see also some correlation id etc.
 
The reason is that by default when you create your web control ASCX the markup is e.g.:
<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="mfsListRow.ascx.vb" Inherits="Malcan.Forms.forSharepoint.mfsListRow" %>
 
There are two solutions for ASCX controls:
- Either put your dll also in the BIN folder of your web application (c:\inetpub\wwwroot\wss\VirtualDirectories\80\bin) (apparantly just to have it there because you still need your assembly in GAC)
- Either (better) change your markup to reflect full assembly name e.g.
<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="mfsListRow.ascx.vb" Inherits="Malcan.Forms.forSharepoint.mfsListRow, Malcan.Forms.forSharepoint, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cafc33df38878ad3" %>
 
For ASPX pages it is a bit different:
- Before your first list in ASPX file <%@ Page  add a new line referencing your assembly in the GAC e.g.
<%@ Assembly Name="Malcan.Forms.forSharepoint.mfsListRow, Malcan.Forms.forSharepoint, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cafc33df38878ad3" %>
Expand/Collapse Technology : JavaScript ‎(3)
 Cookies - examples
function createCookie(name,value,days) {
 if (days) {
  var date = new Date();
  date.setTime(date.getTime()+(days*24*60*60*1000));
  var expires = "; expires="+date.toGMTString();
 }
 else var expires = "";
 document.cookie = name+"="+value+expires+"; path=/";
}
 
function readCookie(name) {
 var nameEQ = name + "=";
 var ca = document.cookie.split(';');
 for(var i=0;i < ca.length;i++) {
  var c = ca[i];
  while (c.charAt(0)==' ') c = c.substring(1,c.length);
  if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
 }
 return null;
}
 
function eraseCookie(name) {
 createCookie(name,"",-1);
}
 CountDown - counting down till your launch
I found it useful and easy to adopt (following DynamicDrive):
<style style="text/css">
.lcdstyle{ /*Example CSS to create LCD countdown look*/
background-color:brown;
color:yellow;
font: bold 24px MS Sans Serif;
padding: 5px;
}
.lcdstyle sup{ /*Example CSS to create LCD countdown look*/
font-size: 80%
}
</style>
<script type="text/javascript">
/***********************************************
* Dynamic Countdown script- © Dynamic Drive (
http://www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit
http://www.dynamicdrive.com/ for this script and 100s more.
***********************************************/
function cdtime(container, targetdate){
if (!document.getElementById || !document.getElementById(container)) return
this.container=document.getElementById(container)
this.currentTime=new Date()
this.targetdate=new Date(targetdate)
this.timesup=false
this.updateTime()
}
cdtime.prototype.updateTime=function(){
var thisobj=this
this.currentTime.setSeconds(this.currentTime.getSeconds()+1)
setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
}
cdtime.prototype.displaycountdown=function(baseunit, functionref){
this.baseunit=baseunit
this.formatresults=functionref
this.showresults()
}
cdtime.prototype.showresults=function(){
var thisobj=this

var timediff=(this.targetdate-this.currentTime)/1000 //difference btw target date and current date, in seconds
if (timediff<0){ //if time is up
this.timesup=true
this.container.innerHTML=this.formatresults()
return
}
var oneMinute=60 //minute unit in seconds
var oneHour=60*60 //hour unit in seconds
var oneDay=60*60*24 //day unit in seconds
var dayfield=Math.floor(timediff/oneDay)
var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour)
var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute)
var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute))
if (this.baseunit=="hours"){ //if base unit is hours, set "hourfield" to be topmost level
hourfield=dayfield*24+hourfield
dayfield="n/a"
}
else if (this.baseunit=="minutes"){ //if base unit is minutes, set "minutefield" to be topmost level
minutefield=dayfield*24*60+hourfield*60+minutefield
dayfield=hourfield="n/a"
}
else if (this.baseunit=="seconds"){ //if base unit is seconds, set "secondfield" to be topmost level
var secondfield=timediff
dayfield=hourfield=minutefield="n/a"
}
this.container.innerHTML=this.formatresults(dayfield, hourfield, minutefield, secondfield)
setTimeout(function(){thisobj.showresults()}, 1000) //update results every second
}
/////CUSTOM FORMAT OUTPUT FUNCTIONS BELOW//////////////////////////////
//Create your own custom format function to pass into cdtime.displaycountdown()
//Use arguments[0] to access "Days" left
//Use arguments[1] to access "Hours" left
//Use arguments[2] to access "Minutes" left
//Use arguments[3] to access "Seconds" left
//The values of these arguments may change depending on the "baseunit" parameter of cdtime.displaycountdown()
//For example, if "baseunit" is set to "hours", arguments[0] becomes meaningless and contains "n/a"
//For example, if "baseunit" is set to "minutes", arguments[0] and arguments[1] become meaningless etc

function formatresults(){
if (this.timesup==false){//if target date/time not yet met
var displaystring=arguments[0]+" days "+arguments[1]+" hours "+arguments[2]+" minutes "+arguments[3]+" seconds left until site is available"
}
else{ //else if target date/time met
var displaystring="Future date is here!"
}
return displaystring
}
function formatresults2(){
if (this.timesup==false){ //if target date/time not yet met
var displaystring="<span class='lcdstyle'>"+arguments[0]+" <sup>days</sup> "+arguments[1]+" <sup>hours</sup> "+arguments[2]+" <sup>minutes</sup> "+arguments[3]+" <sup>seconds</sup></span><BR><BR><BR>left until
http://malcan.com is available..."
}
else{ //else if target date/time met
var displaystring="" //Don't display any text
alert("Please go to
http://malcan.com. It is available!") //Instead, perform a custom alert
}
return displaystring
}
</script>
<BODY>
<div id="countdowncontainer"></div>
<br />
<div id="countdowncontainer2"></div>
<script type="text/javascript">
var futuredate=new cdtime("countdowncontainer", "December 1, 2008 00:00:00")
futuredate.displaycountdown("days", formatresults2)
</script>
</BODY>
 Redirecting to language sites
If you want your users to be automatically redirected to different language sites based on their regional settings you may try script that works for me (just add it to your main page in the most upper section before <html> starts):
<script>
//Enter ISO 639-2 letter Language codes to detect (see:
http://www.w3.org/WAI/ER/IG/ert/iso639.htm):
var langcodes=new Array("pl", "default")
//Enter corresponding redirect URLs (last one is for default URL):
var langredirects=new Array("/pl/Wiki%20Pages/Home.aspx", "/en/Wiki%20Pages/Home.aspx")
var languageinfo=navigator.language? navigator.language : navigator.userLanguage
var gotodefault=1
function redirectpage(dest){
if (window.location.replace)
window.location.replace(dest)
else
window.location=dest
}
for (i=0;i<langcodes.length-1;i++){
if (languageinfo.substr(0,2)==langcodes[i]){
redirectpage(langredirects[i])
gotodefault=0
break
}
}
if (gotodefault)
redirectpage(langredirects[langcodes.length-1])
</script>
Expand/Collapse Technology : Office365 (sandbox) ‎(1)
 How to add event receiver directly to content type
As you know it is not possible to add one programmatically since
contentType.EventReceivers.Add();
is not allowed in sandboxed solutions.
 
What is possible? Of course the declarative way (elements.xml file of your content type):
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="
http://schemas.microsoft.com/sharepoint/">
  <!-- Parent ContentType: Item (0x01) -->
  <ContentType ID="0x0100e73408ecaffc4aaaa0623ef487cbd2cc"
               Name="aName"
               Group="aGroup"
               Description="My Content Type"
               Inherits="TRUE"
               Version="0">
    <FieldRefs>
    </FieldRefs>
    <XmlDocuments>
      <XmlDocument NamespaceURI="
http://schemas.microsoft.com/sharepoint/events">
        <spe:Receivers xmlns:spe="
http://schemas.microsoft.com/sharepoint/events">
          <Receiver>
            <Name>aHandler</Name>
            <Type>ItemAdding</Type>
            <SequenceNumber>10000</SequenceNumber>
            <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
            <Class>Namespace.aClass</Class>
          </Receiver>
        </spe:Receivers>
      </XmlDocument>
    </XmlDocuments>
  </ContentType>
</Elements>

Unfortunately that is not that easy. In order for XmlDocuments to work you may not inherit... So if you still need to use it you must:
1) Change to Inherits="FALSE"
2) Add all your fields into the <FieldRefs> e.g. at least the default Title
      <FieldRef ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" Name="Title" />
 
Seems like candidate for improvement for the next Office365 version.
Expand/Collapse Technology : Outlook ‎(1)
 Outlook connector update problem v.12.1
When you open Outlook you get the following message:
To continue accessing your mail using Microsoft Office Outlook, you must upgrade to the latest version of Outlook connector.
If you choose to upgrade now, Microsoft Office Outlook will close and restart.
 
What helped me was:
- manually close Outlook, close live messenger, uninstall Outlook Connector (from Control Panel)
- restart
- download manually Outlook Connector v.12.1 and install again
- run Outlook
Expand/Collapse Technology : SharePoint 2007 ‎(9)
 Cannot find anything with SPQuery CAML and GetItems when searching against URL field
When you want to look for items on the list or library searching with CAML by URL field you find zero items... although the URL is there.
 
The typical CAML string is below:
<Where>
   <BeginsWith>
      <FieldRef Name='URL'/>
      <Value Type='Text'>http://server/file.txt</Value>;
   </BeginsWith>
</Where>
 
Typical C# code to use SPQuery is:
SPSite oSite = new SPSite("http://moss");
SPWeb oWeb = oSite.OpenWeb();
SPList oList = oWeb.GetListFromUrl("Lists/Links/AllItems.aspx");
SPQuery linksQuery = new SPQuery();
linksQuery.Query = this.txtCAML.Text;
MessageBox.Show(oList.GetItems(linksQuery).Count.ToString());
 
There are few things you may wonder:
1) Should I use <Eq> or <BeginsWith> or <Contains> tag => in my case it turned out BeginsWith works fine (as URL is encoded as "URL, Title" in the field).
2) Shoold the value type be 'Text' or 'Url' => in my case it turned out both are equal.
3) Why the hell I cannot find my items (returns zero)? => it turns out the rules are as follows:
   a) IF you look for link that points to the same Sharepoint box THEN you should search with relative URL (so the caml value is just /file.txt and not http://server/file.txt.
   b) IF you look for link that points to any other box or even the same box with different port number (e.g. http://server:81/file.txt) THEN you should use full URL as in the CAML example above.
 Custom ASP.Net page on Sharepoint
Just two steps are required:
1. Copy assembly to your wwwroot/bin subfolder.
2. Copy your ASPX files e.g. to layouts sharepoint subfolder.
3. (OPTIONAL) If you are to access Sharepoint API you need to set change WSS_Minimal to WSS_Medium in SharePoint web.config.
 
Advantages:
- You don't need to sign assemblies.
- You don't need to register assemblies in GAC.
- It is very EASY and FAST deployment - especially when developing/testing. You don't need to restart IIS server (or App Pool) in order for changes to take effect. In VS.Net you may create a script running after build process so anytime you build your changes are visible in Sharepoint.
 
Disadvantages:
- You don't follow Microsoft guidelines with features & solutions so in farms you need to repeat these steps on every front end server.
 How to avoid events in event handler
When you are implementing an event handler and want to change other data without running into other event handlers you need to disable them first.
 
this.DisableEventFiring();
  SPListItem item = properties.ListItem; 
   item["test"] = "newValue";
  item.Update();
this.EnableEventFiring();
 
Note: when you do SystemUpdate() instead of Update() you don't increase version number on the item.
 Sharepoint guidelines and limitations
Sharepoint limits and guidelines is one of the most frequently asked questions (following Microsoft - source 2008-12-11 from: http://technet.microsoft.com/en-us/library/cc262787.aspx)
 
Site object  Guidelines for acceptable performance  Notes  Scope of impact when performance degrades 
Site collection
 50,000 per content database
 Total farm throughput degrades as the number of site collections increases.
 Farm
 
Site collection
 150,000 per Web application
 This limit is theoretical, and is dependent largely upon:
Performance of the database server on which the configuration database resides.
Performance of the Web servers in the farm.
Network bandwidth between the Web servers and the database server.
This is not a hard limit, and assumes a single database server. Your environment may not be able to host this many site collections per Web application. Distributing content databases across additional database servers can increase the effective limit of the number of site collections per Web application. You should perform testing to determine the actual effective limit in your environment.
 Farm
 
Web site
 250,000 per site collection
 You can create a very large total number of Web sites by nesting the subsites. For example, 100 sites, each with 1000 subsites, is 100,000 Web sites. The maximum recommended number of sites and subsites is 125 sites with 2,000 subsites each, for a total of 250,000 sites.
 Site collection
 
Subsite
 2,000 per Web site
 The interface for enumerating subsites of a given Web site does not perform well as the number of subsites surpasses 2,000.
 Site view
 
Document
 5 million per library
 You can create very large document libraries by nesting folders, using standard views and site hierarchy. This value may vary depending on how documents and folders are organized, and by the type and size of documents stored.
 Library
 
Item
 2,000 per view
 Testing indicates a reduction in performance beyond two thousand items. Using indexing on a flat folder view can improve performance.
 List view
 
Document file size
 50MB (2GB max*)
 File save performance is proportional to the size of the file. The default maximum is 50 MB. This maximum is enforced by the system, but you can change it to any value up to 2 GB.
 Library, file save performance
 
List
 2,000 per Web site
 Testing indicates a reduction in list view performance beyond two thousand entries. For more information about large lists, see White paper: Working with large lists in Office SharePoint Server 2007.
 List view
 
Field type
 256 per list
 This is not a hard limit, but you might experience list view performance degradation as the number of field types in a list increases.
 List view
 
Column
 2,000 per document library
4,096 per list
 This is not a hard limit, but you might experience library and list view performance degradation as the number of columns in a document library or list increases.
 Library and list view
 
Web Part
 50 per page
 This figure is an estimate based on simple Web Parts. The complexity of the Web Parts dictates how many Web Parts can be used on a page before performance is affected.
 Page
 
Managed path
 20 per Web application
 20 managed paths is a soft limit. Managed paths are cached on the Web server, and CPU resources are used to process incoming requests against the managed path list. You should test for performance before exceeding 20 managed paths in a single Web application.
 Web application
 
The following table lists the recommended guidelines for people objects.
People object  Guidelines for acceptable performance  Notes 
Users in groups
 2 million per Web site
 You can add millions of people to your Web site by using Microsoft Windows security groups to manage security instead of using individual users.
 
User profile
 5 million per farm
 This number represents the number of profiles which can be imported from a directory service, such as Active Directory, into the people profile store.
 
Security principal
 Approximately 2,000 per ACL (Access Control List) on any securable object (scope)
 The total size of the ACL on scopes can be no larger than 64kb. Because each security principal is approximately 32 bytes in size, there can be no more than approximately 2,000 security principals or less for each scope.  If this limit is reached, indexing of items in that scope, and all items below that scope, to fail.
Also, because SharePoint Groups are expanded during the indexing process, having more than 2,000 users or Directory Groups in a SharePoint group and using that group for securing scopes may cause indexing of items secured with these groups, and all items below them, to fail.
This limit only occurs when Windows Integrated Authentication is utilized.
 
The following table lists the recommended guidelines for search objects.
Search object  Guidelines for acceptable performance  Notes 
Search indexes
 One per SSP
Maximum of 20 per farm
 Office SharePoint Server 2007 supports one content index per SSP. Given that we recommend a maximum of 20 SSPs per farm, a maximum of 20 content indexes is supported.
Note that an SSP can be associated with only one index server and one content index. However, an index server can be associated with multiple SSPs and have a content index for each SSP.
 
Indexed documents
 50,000,000 per content index
 Office SharePoint Server 2007 supports 50 million documents per index server. This could be divided up into multiple content indexes based on the number of SSPs associated with an index server.
 
Content sources
 500 per SSP*
 This is a hard limit enforced by the system.
 
Start Addresses
 500 per content source*
 This is a hard limit enforced by the system.
 
Alerts
 1,000,000 per SSP
 This is the tested limit.
 
Scopes
 200 per site
 This is a recommended limit per site. We recommend a maximum of 100 scope rules per scope.
 
Display groups
 25 per site
 These are used for a grouped display of scopes through the user interface.
 
Crawl rules
 10,000 per SSP
 We recommend a maximum 10,000 crawl rules irrespective of type.
 
Keywords
 15,000 per site
 We recommend a maximum of 10 Best Bets and five synonyms per keyword.
 
Crawled properties
 500,000 per SSP
 These are properties that are discovered during a crawl.
 
Managed properties
 100,000 per SSP
 These are properties used by the search system in queries. Crawled properties are mapped to managed properties. We recommend a maximum of 100 mappings per managed property.
 
Authoritative pages
 200 per relevance level
 This is the maximum number of sites in each of the four relevance levels.
 
Results removal
 100
 This is the maximum recommended number of URLs that should be removed from the system in one operation.
 
Crawl logs
 50,000,000
 Number of individual log entries in the crawl log.
 
The following table lists the recommended guidelines for logical architecture objects.
Logical architecture object  Guidelines for acceptable performance  Notes 
Shared Services Provider (SSP)
 3 per farm (20 per farm maximum)
   
Zone
 5* per farm
 The number of zones defined for a farm is hard coded to 5.
 
Web application
 99 per SSP
 This limit includes the number of Web applications on child farms consuming resources on this SSP.
 
Internet Information Services (IIS) application pool
 8 per Web server
 Maximum number is determined by hardware capabilities.
 
Site collection
 50,000 per Web application
 
 
Content database
 100 per Web application
 
 
Site collection
 50,000 per database
 
The following table lists the recommended guidelines for physical objects.
Physical object  Guidelines for acceptable performance  Notes 
Index servers
 1 per SSP*
 
Application servers running Excel Calculation Services
 No limit
 
Query servers
 No limit
 Because 100 content databases are supported for each query server, the number of query servers required per farm is based on the number of content databases in the farm. For example, if there are 500 content databases in your farm, you will need at least 5 query servers.
 
Web server/database server ratio
 8 Web servers per database server
 The scale out factor is dependent upon the mix of operations.
 
Web server/domain controller ratio
 3 Web servers per domain controller
 Depending on how much authentication traffic is generated, your environment may support a greater number of Web servers per domain controller.
 Simple feature with ListItem event handler
First we need some piece of code of our event handler (this is simple class library, add Microsoft.SharePoint reference in your project first):
Imports Microsoft.SharePoint
Public Class ListItemHandler
    Inherits SPItemEventReceiver
    Public Overrides Sub ItemAdding(ByVal properties As SPItemEventProperties)
        properties.Cancel = True
        properties.ErrorMessage = "some error"
    End Sub
End Class
 
The code above simply does not allow you add add anything to your list - you will always get an error. If it does not work later on remember to check Windows Event Log.
 
Then we need to sign this project and deploy it into GAC. Remember that gacUtil comes with VS SDK (not VS itself). You may use this syntax:
"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe" /i myHandler.dll
 
Now we need the FEATURE.XML (kind of manifest file telling what you are declaring in advance) and child file ELEMENTS.XML (at least usually called so). You also need unique GUID for your feature. Both files should be created under your newly created feature's folder e.g. C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\myFeature
 
Example of FEATURE.XML is:
<?xml version="1.0" encoding="utf-8"?>
<Feature
  Id="ddeefbb1-cff7-4198-9170-f1a477168e5f"
  Title="myHandler"
  Description="This feature enables ..."
  Scope="Web"
  xmlns="
http://schemas.microsoft.com/sharepoint/">
 <ElementManifests>
  <ElementManifest Location="elements.xml" />
  </ElementManifests>
</Feature>

Example of ELEMENTS.XML is (be carefull with ListTemplateId - currently it means any custom list and not e.g. tasks or announcements):
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
   <Receivers ListTemplateId="100">
      <Receiver>
         <Name>ItemAdding</Name>
         <Type>ItemAdding</Type>
         <SequenceNumber>10000</SequenceNumber>
         <Assembly>MyHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5a337b9e4432caf4</Assembly>
         <Class>MyNamespace.MyHandler</Class>
         <Data></Data>
         <Filter></Filter>
      </Receiver>
   </Receivers>
</Elements>
 
Then it is enough to install feature and then activate it on some web site:
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN"\stsadm -o installfeature -filename MyFeature\Feature.xml
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN"\stsadm -o activatefeature -filename MyFeature\Feature.xml -url http://malcan/mysubSite
 
Just in case you will do it many times it is usefull that:
- In order to republish assembly in GAC you can just run above import again and again (iisreset or faster application pool reset is necessary)
- In order to republish feature you need deactivate it and uninstall it:
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN"\stsadm -o deactivatefeature -filename MyFeature\Feature.xml -url http://malcan/mysubSite
"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN"\stsadm -o uninstallfeature -filename MyFeature\Feature.xml
 Sometimes your asynchronous post events ItemAdded ItemUpdated don't run from Console Application
The reason is funny, but it is that your application quits faster than the output can be received from SharePoint - so eventually it fails without any error in the event log or any log in 12 hive.
 
It is even stranger to catch the difference because all your synchronous events fire properly like ItemAdding, ItemUpdating.
 
So the workaround is to let this thread calling asynchronous events wait a bit e.g. with System.Threading.Thread.Sleep(1000);
 AttachmentWiki page changed - removed Edit, History, Incoming Links, also more webparts
Standard wiki page seems to a bit strange because:
- it has just one bottom zone available for webparts
- for anonymous users it does not hide unneeded links like Edit, History, Incoming Links (for some reasons it is not security trimmed by Sharepoint itself)
- also "Last modified" section is under the bottom webparts what is strange, because everybody may think these are the modification dates for webparts and not for wiki page itself.
 
Enclosing changed wiki template that addresses above (feel free to get attached version from this item):
- It adds a right zone for webparts (as you may see also on http://malcan.com/EN/Wiki%20Pages/Competencies.aspx) - it is safe for you just to replace your aspx wiki pages using Windows Explorer - your content will be displayed as it was before (since all the content comes from database and not from this look and feel page).
- It hides the unneeded for end users links like Edit, History, Incoming Links.
- It moves "Last modified" wiki section up so it is now located between wiki content and bottom webparts zone.
 You are recognized as Sharepoint\system
Sometimes once logged to SharePoint (WSS or MOSS) you are recognized as SharePoint\System account (instead being recognized as your domain\alias.
 
Additionally once you play with SharePoint groups you may observe that whenever you create such group you are not visible member although you are recognized member. It looks strange because:
- Whenever you try to add yourself SharePoint's UI (without any error) does not put you on the list of members
- Since you don't see yourself as a member you cannot remove yourself.
- If you use this group you are recognized as member of this group
- If you use Sharepoint SDK SPGroups.Users or SPGroup.SiteUsers you see administrator (usually) as a member.
 
The reason for that is you have set up your SharePoint service accounts using your own credentials e.g. for configuration database access, for search etc. This is common mistake and if you are already in that situation you may do:
1) Preferred - changing all the accounts so your personal credentials are not used for service accounts (good article is http://support.microsoft.com/kb/934838)
2) Reinstall your environment using service accounts and restoring your backups.
 
Also you need to delete wrongly created groups and recreate them as domain user.
 You cannot type some Polish letters in the Rich Text Editor od in Datasheet View (problem res://ieframe.dll)
After you apply the Service Pack 1, run the STSADM utility to enable this fix. Use the following command:
stsadm.exe -o setproperty -url http://portal -pn "richtexteditorshortcutenabled" -pv "no"
Note:
portal is your portal site location, stsadm by default is in C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN
 
Workaround: if you cannot deploy the change above you may enter Polish characters not with ALT, but with SHIFT, ~, release keys and then l for ł etc.
 
Notes after applying SP2 or when running Office 2010:
- Normally the behaviour above should solved automatically.
- You may experience another problem with IE stops working (res://ieframe.dll) when entering some of special characters (like Polish ńę) only in DataSheet view. For that to be running smoothly you need to go to manage your IE Add On and DISABLE Microsoft IE Add-Ons one by one checking which one is causing the problem. For me it helped to disable SharePoint Export Database Launcher, SharePoint SpreadSheet Launcher, SharePoint STSSYNC Handler...
Expand/Collapse Technology : SharePoint 2007 2010 ‎(1)
 HTML document does not contain Web service discovery information
When you run Disco.exe against your asmx file you may experience very inconvenient message "HTML document does not contain Web service discovery information".
 
In my case there were three things I had to check/update:
1) If you declare you class with assembly name in the asmx file. Pretty sure you have already got that and still struggle the problem.
2) Permissions in 12 or 14 hive, check if WSS_WPG has modified access there.
3) Last and not least is try to copy your ASMX file into accessible folder like ...12\TEMPLATE\LAYOUTS. Then just access your file with http://YourServer/_Layouts/YourFile.asmx. Remember to have errors visible (in your web.config in both places Layouts folder and then one in your web application C:\Inetpub\wwwroot\wss\VirtualDirectories\80 has <customErrors mode="Off" /> and CallStack="true" ). SO YOU MAY EASILY SEE WHAT THE PROBLEM IS. In my case I had some classes with interfaces that could not be serialized.
 
Hope it helps
Expand/Collapse Technology : SharePoint 2010 ‎(2)
 Search results appear for deleted items (The object was not found)
When you search you may see too many results, once you click on particular result item you see the item is no longer available.
 
When you then investigate Search errors in Search Administration you may notice errors like "The object was not found".
 
The reason for this is Sharepoint needs some time to really be sure to remove it from index and eventually from your result sets.
 
As stated in http://technet.microsoft.com/en-us/library/hh127009.aspx you can manually modify two attributes with powershell to eliminate that behaviour. In my case it is very frequent need to add/remove some items and have results up to date.
 
What worked for me was first checking current values for two properties:
 
$SearchApplication = Get-SPEnterpriseSearchServiceApplication -Identity "Search Service Application"
 
$SearchApplication.GetProperty("ErrorDeleteCountAllowed")
30

$SearchApplication.GetProperty("ErrorDeleteIntervalAllowed")
720
 
And then set them appropriately:
$SearchApplication.SetProperty("ErrorDeleteCountAllowed", 1)
$SearchApplication.SetProperty("ErrorDeleteIntervalAllowed",0)
 
Rebuild index with crawl (incremental is OK).
That's it.
 
P.S.
Values 0, 1 are good only for dev/test environments:)
 The list cannot be displayed in Datasheet view (standard view works only)
Dialog windows says additionally:
- A datasheet component compatible with Microsoft SharePoint Foundation is not installed.
- Your Web browser does not support ActiveX controls.
- A component is not properly configured for 32-bit or 64-bit support.
Solution which worked on Win2008 R2 64 bit with SPF 2010 is to install ...
1) 2007 Office System Driver: Data Connectivity Components (AccessDatabaseEngine.exe) from http://www.microsoft.com/downloads/details.aspx?familyid=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en and then
2) and then Microsoft Office Access Runtime and Data Connectivity 2007 Service Pack 2 (SP2) (accessruntimeanddataconnectivity2007sp2-kb957262-fullfile-en-us.exe) from http://www.microsoft.com/downloads/details.aspx?FamilyId=6F4EDEED-D83F-4C31-AE67-458AE365D420&displaylang=en
 
Check also problems with Datasheet view regarding some special characters here.
Expand/Collapse Technology : SQL Server ‎(1)
 Rows counts - getting quickly, comparing databases
Just to get all tables with their row counts quickly:
select so.name, si.rows
from sysindexes si inner join sysobjects so on si.id=so.id
where si.indid<2 and so.xtype='U'
order by si.rows desc
 
Also a combination if you want to compare rows counts between two databases e.g. to check if they are the same (in terms of row counts).
select so1.name, si1.rows, si2.rows, si1.rows-si2.rows from DB1..sysindexes si1
 inner join DB1..sysobjects so1 on si1.id=so1.id
 inner join DB2..sysobjects so2 on so1.name=so2.name
 inner join DB2..sysindexes si2 on si2.id=so2.id
 where si1.indid<2 and so1.xtype='U'and si2.indid<2 and so2.xtype='U' and si1.rows-si2.rows<>0
 order by so1.name
 
Note:
The results may be not accurate due to the values in SQL system tables (it may require exhoustive DBCC UPDATEUSAGE). Usually they are correct and if you really want to compare I would suggest to use this script first and then investigate just few differences.
It works only on tables with an index on them.
Expand/Collapse Technology : Virtual PC ‎(1)
 Windows Virtual PCs Frequently Stop Responding For Short Periods
It turns out the after moving to Windows Virtual PC (Windows 7) my guest operating systems were stopping for short time, which was really nervous. Screen was not reflecting quickly my keyboard changes when typing. I was surprised because my newer machine was better than previous one.
 
Occasionally I have checked that Windows Virtual PC has USB menu with some devices not attached. When I just attached the devices it started to work quickly :) (even stopping the device installation process later).
Expand/Collapse Technology : XML & XSL ‎(1)
 AttachmentSimple HTML page based on XML and XSL
XML
<?xml version='1.0'?>
<?xml-stylesheet type="text/xsl" href="test.xsl"?>
<wholeDocument>
  <folder path="c:\malcan">
     <file path="c:\malcan\file1.txt"/>
     <file path="c:\malcan\file2.txt"/>
  </folder>
</wholeDocument>
 
XSL
<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  
 <xsl:template match="/">
  <HTML>
   <BODY>
    <TABLE>
     <xsl:apply-templates select="//folder"/>
    </TABLE>
   </BODY>
  </HTML>
 </xsl:template>
 
 <xsl:template match="folder">
  <tr>
   <td>Folder <b><xsl:value-of select="@path"/></b> has </td>
   <td><xsl:value-of select="count(file)"/> files</td>
  </tr>
 </xsl:template>
</xsl:stylesheet>
 
Find attached files test.xml and test.xsl, please. It is easy just to download them and open test.xml in the browser.