Impersonate another user c#

on Friday, December 4, 2009

public class Impersonator
{
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;

WindowsImpersonationContext impersonationContext;

[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);



public bool impersonate(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;

if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}

public void undoImpersonation()
{
impersonationContext.Undo();
}
}

//Sample Code

Impersonator imp = new Impersonator();
bool isTrue=imp.impersonate("testuser1", "buildmachine", "password");
if (isTrue)
{
items = testDocLib.GetItems(query);

Console.WriteLine(items.Count);
imp.undoImpersonation();
}

SharePoint Hard Limits and Recommendation

on Thursday, December 3, 2009

Entity Max Permissible Size
Site Name 128 characters
Site URL 255 characters
Display name 128 characters
Connection string 384 characters
Email address 128 characters
Version numbers 064 characters
Virtual Server Friendly Name 064 characters
SQL Database Name 123 characters
SQL Database Column 128 characters
SQL Database Table Name 128 characters
SQL Role Name 128 characters
Server Name 128 characters
Windows User Name 300 characters
Windows Password 300 characters
Dependencies per object 032 objects
Zone enumeration value 004 zones
Default SQL command timeout 300 seconds
Number of simultaneous workflows that can be run 015


Site object

Guidelines for acceptable performance Notes Scope of impact when performance degrades
Site collection 50,000 per Web application Total farm throughput degrades as the number of site collections increases. 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. 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 library4,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

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 2,000 per Web site The size of the access control list is limited to a few thousand security principals (users and groups in the Web site).

The following table lists the recommended guidelines for search objects.


Search object

Guidelines for acceptable performance Notes
Search indexes One per SSPMaximum 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.

SPSiteDataQuery example

on Wednesday, December 2, 2009

I have been playing with the SPSiteDataQuery a fair bit recently and thought it would be interesting to post some of the results.

When using the SPSiteDataQuery to perform a search there are four main properties you are going to set which determine the results you will get. If you have seen my previous post (XML results using SPSiteDataQuery in SharePoint) you will have seen that they are Lists, Query, Webs and ViewFields.

If you read nothing else then remember this...If you make a mistake in the Webs or Lists properties, invalid XML or invalid attributes, the SPSiteDataQuery will fall back to it's default behavior and will not throw an error!! Knowing this can save a lot of time...ensure your properties are correctly formatted.

So, assuming the basic setup is

SPSiteDataQuery q = new SPSiteDataQuery();
q.Lists = "<Lists BaseType='1'/>";
q.Query = "<Where><Gt><FieldRef Name='ID' /><Value Type='Number'>0</Value></Gt></Where>";
q.Webs = "<Webs Scope='SiteCollection' />";
q.ViewFields = "<FieldRef Name='Title' /><FieldRef Name='ID' />"';
q.RowLimit = 10;

Here are the changes you can make to achieve different result sets and tips as to why the query could be failing.

 

The Webs Property

There are basically three different values for this...


"<Webs Scope='SiteCollection' />" This will search the entire site collection no matter which web you use to execute the query.
"<Webs Scope='Recursive' />" This will search the web on which you execute the query and recurse through any child webs.

"" If you leave it blank then it will only search the web on which you execute the query. No child webs will be queried. This is important as I have read on several other sites that this is not possible with SPSiteDataQuery, but it is!!

I would also point out that that if you get anything wrong with this property SharePoint will not throw an error, it will just default to the blank behavior...It will only search the web on which you executed the query. This is an important point as "<Webs scope='Recursive' />"  or "<Webs Scope='recursive' />" (small 's' in Scope and small 'r' in recursive) look OK but are actually invalid and the query will default to only the current web.

 

The Lists Property

This defines what type of document libraries and lists WSS will search for your items. You can specify the exact type of list, the base type or even specific lists. Examples of the Lists property are...

"<Lists BaseType='1'/>" As above, this will search all lists which are based on a 'Document Library. This is useful if you only want to find documents. Other values for BaseType include...

0 - Generic list - This will search all lists and not document libraries.
1 - Document Library
3 - Discussion Forum
4 - Vote or Survey
5 - Issues list

(no, I don't know what happened to number 2!!)

I should also point out that the default is to search BaseType = '0' , and so if you do not set or make a mistake in the XML only lists will be searched.

"<Lists ServerTemplate='850'/>" This will limit the search to only a particular list template (850 is the Pages template in a publishing site). The number is fairly random and is defined in the list definition. I haven't needed to look at them as yet so I don't know a better way than looking in the definitions in the FEATURES folder for SharePoint. If you make a mistake with this property it will revert to the default.

Another options is Hidden, which determines if hidden lists or document libraries are searched. This an additional attribute and would be used like this...

"<Lists ServerTemplate='850' Hidden='TRUE'/>"

The MaxListLimit attribute specifies the total number of lists to search. You will receive an exception if the query exceeds the MaxListLimit. The default amount is 1000 and by setting this to 0 you can search everything. So the following would only search the first 50 lists...

"<Lists BaseType='1' MaxListsLimit='50'/>"

Another thing you can do with the Lists property is to query specific lists. This can be done by specifying the Guid of the list you want to search. An example would be...

"<Lists><List ID="129AB4CAE-12EF-9871-DE45-F34A180D3EAB5"/></Lists>"

You would obviously need to know the Guid of the lists you wish to query before creating this property.

 

The ViewFields property

The ViewFields property specifies the fields (columns), that will be returned in the query. This is very similar to SQL and you should ensure that you specify any fields that you may wish to use in you Where or OrderBy part of the query.

Things to point out here is that that you can specify the ID(Guid) of the property or the name of the property...this is the Internal Name, not the name you may see in the UI. For example the standard publishing field "Image Caption" would become "PublishingImageCaption" as that is it's internal name.

So, to add the "Image Caption" filed to the results we would need...

"<FieldRef Name='Title' /><FieldRef Name='ID' /><FieldRef Name='PublishingImageCaption' />"

Another thing to remember is that not all lists or documents libraries contain the same fields. If you are not worried about a particular field and want the item returned whether the field (column) exists or not the you can set Nullable to true. So if we have some items which may not have an 'Image Caption' column then we could use...

"<FieldRef Name='Title' /><FieldRef Name='ID' /><FieldRef Name='PublishingImageCaption' Nullable='TRUE'/>"

and this would still find those items without an 'Image Caption' column (field).

 

The Query Property

This property will allow you to bot limit and order you results. You can do both or just one, but it is similar to SQL in what you can do. There is a lot to this, but I will give a couple of samples...

Querying by date...

string sLastWeek = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Today.AddDays(-1));
q.Query = "<Where><Gt><FieldRef Name='Created'><Value Type='DateTime'>" + sLastWeek + "</Value></Gt></Where>";

This will find items created within the last week. The <Gt> denotes 'Greater Than', you could also use <Gte>, <Lt> or <Eq>. These can be combined to create more complex queries.

q.Query = "<OrderBy><FieldRef Name='Title' Ascending='FALSE'></OrderBy>";

This will order the items descending by the title (Z-A).

q.Query = "<Where><Gt><FieldRef Name='Created'><Value Type='DateTime'>" + sLastWeek + "</Value></Gt></Where><OrderBy><FieldRef Name='Title' Ascending='FALSE'></OrderBy>";

This is a combination of the above...items created in the last week ordered Z-A.

Finally, make sure you set the RowLimit property...you may not get any results otherwise!!