Friday, December 24, 2010

Editcontrolblock-customaction-for-sharepoint


Editcontrolblock-customaction-for-sharepoint

Thursday, December 23, 2010

Using Javascript code to show/hide controls in NewForm or EditForm.

You can use the following javascript code to show/ hide controls in NewForm or EditForm.

< script type="text/javascript" >

_spBodyOnLoadFunctionNames.push("hideFieldsOnStart");

function hideFieldsOnStart() {

//hide the control at startvar control = getTagFromIdentifierAndTitle("input","TextField","FieldDisplayName");

control.parentNode.parentNode.parentNode.style.display="none";

//add an onchange event to the dropdown
getTagFromIdentifierAndTitle("select","DropDownChoice","DropDownDisplayName").onchange = function() {ChangeEvent()};


}


function ChangeEvent()
{

//get the dropdownvar dropdown = getTagFromIdentifierAndTitle("select","DropDownChoice","DropDownDisplayName");

//get the selected valuevar option = dropDown.options[dropDown.selectedIndex].text;

//get the controlvar control = getTagFromIdentifierAndTitle("input","TextField","FieldDisplayName");

//show hide based on your conditionif(option == "xyz")
{
control.parentNode.parentNode.parentNode.style.display="";
}
else
{
control.parentNode.parentNode.parentNode.style.display="none";
}

//this gets the field based on title identifier and tagnamefunction getTagFromIdentifierAndTitle(tagName, identifier, title) {
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++) {
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len)) {
return tags[i];
}
}
returnnull;
}
</script >

List of sharepoint column types and their corresponding identifiers, tagnames and Title


































































SharePoint Field Type Identifier Tag Name Title
Single Line of Text TextField input Same as Field Title
Multiple Lines of Text TextField input Same as Field Title
Number TextField input Same as Field Title
Currency TextField input Same as Field Title
Choice (dropdown) DropDownChoice select Same as Field Title
Lookup (single)* Lookup select Same as Field Title
Lookup (multiple) SelectCandidate; SelectResult select Same as Field Title
Yes/No BooleanField input Same as Field Title
People or Group UserField_downlevelTextBox textarea People Picker

(It must be

People Picker only. Irrespective of Filed name)


It depends what type of field you are trying hide it is in your case
if text field it should be
var control = getTagFromIdentifierAndTitle("input","TextField","FieldDisplayName");

if choice

var control = getTagFromIdentifierAndTitle("select","DropDownChoice","FieldDisplayName");

if yes/no then

var control = getTagFromIdentifierAndTitle("input","BooleanField","FieldDisplayName");

if Lookup then

var control = getTagFromIdentifierAndTitle("select","Lookup","FieldDisplayName");

If it is People Picker


var control = getTagFromIdentifierAndTitle('textarea','UserField_downlevelTextBox','People Picker');

Adding Context Menu in SharePoint List or Library using Content Editor Web part

< script type="text/javascript">
function Custom_AddListMenuItems(m, ctx) {
CAMOpt(m,'Edit Form(new window)','javascript:window.open(\'EditForm.aspx?ID=' + currentItemID + '\');','/_layouts/images/LIST.GIF');
// false means that the standard menu items should also be rendered
// if you set true, it will show only the menu which you added( standard sharepoint menu items will not be available.
// you can control by setting the value of true or false
return true;
}
</script>

If the above function returns false, then the context menu is displayed as below.




If the above function returns true, then the context menu is displayed as below.



Similary if you want to do for List, you have to use the Different method name.

For Document Library : Instead "Custom_AddDocLibMenuItems"

For List : "Custom_AddListMenuItems"

Also you can do following using Script in Content Editor Webpart

To hide the "Delete" (particular) menu item in LibraryContext Menu add this below function

function CAMOpt(p,wzText,wzAct,wzISrc,wzIAlt,wzISeq,wzDesc)
{
var mo=CMOpt(wzText,wzAct,wzISrc,wzIAlt,wzISeq,wzDesc);
if(!mo)return null;
//wzText you can give which one you want hide (like "Edit Properties")
if(wzText != "Delete") AChld(p,mo);
return mo;
}

You can download the script and add it in your content editor webpart; it will take care of the previous actions for document Library.

Use the approriate Script for list / library.
Enjoy!!!...

Using javascript to hide People Picker SharePoint field based on DropDown value

< script type="text/javascript">

_spBodyOnLoadFunctionNames.push("hidePeoplePicker");

function hidePeoplePicker() {
//alert("HIDE");
var control = getTagFromIdentifierAndTitle('textarea','UserField_downlevelTextBox','People Picker');
control.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.style.display="none";

//This code runs on the onchange event of the drop down list field
getField('select','Form Type').onchange = function() {getSecurityLevelValue()};

}

function showPeoplePicker() {
var control = getTagFromIdentifierAndTitle('textarea','UserField_downlevelTextBox','People Picker');
control.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.style.display="";

}




function getTagFromIdentifierAndTitle(tagName, identifier, title) {

//alert("tagName = " + tagName);

var len = identifier.length;
//alert("Len = " + len);

var tags = document.getElementsByTagName(tagName);
//alert("tags length = " + tags.length);

for (var i=0; i < tags.length; i++) {
var tempString = tags[i].id;
var tt = tempString.indexOf(identifier);
var ss = tempString.length - len;
if(tags[i].title == "People Picker")
//alert("tempString = " + tt +"---"+ss );
if (tags[i].title == title && (identifier == "" ||
tempString.indexOf(identifier) == tempString.length - len)) {
return tags[i];
}
}
return null;
}




function getField(fieldType,fieldTitle) {

var docTags = document.getElementsByTagName(fieldType);

//alert("Length = " + docTags.length);

for (var i=0; i < docTags.length; i++) {

if (docTags[i].title == fieldTitle) {

//alert("Value in getField = " + docTags[i].value);

return docTags[i];

}

}

}

function getSecurityLevelValue() {

//alert("In getSecurityLevelValue");
selectedId = getField('select','Form Type').options[getField('select','Form Type').selectedIndex].value;

//alert("Value in hide =" + selectedId);

if(selectedId != 'Org change/ cost centre change')

{

//alert("NOT Specific Request Hide");

hidePeoplePicker();

}

else

{

//alert("Request Show");
showPeoplePicker();

}

}

</script>

Note:-

1) If you have more than one People Picker either in edit form or new form, in that case hidden field should be displayed first and then non hidden people picker in that form. It is done by changing Column order.

Friday, August 6, 2010

Understanding Database Stored Procedures

This article discusses stored procedures and how to create, update, and delete stored procedures using SQL.

What is a Stored Procedure?

A stored procedure is a database object that contains one or more SQL statements. In this article you will get an idea on how to create and use stored procedures and also highlighted on how to use stored procedures.

The first time a stored procedure is executed; each SQL statement it contains is compiled and executed to create an execution plan. Then procedure is stored in compiled form with in the database. For each subsequent execution, the SQL statements are executed without compilation, because they are precompiled. This makes the execution of stored procedure faster than the execution of an equivalent SQL script.

To execute a stored procedure you can use EXEC statement.

CREATE PROC spGetShashiAS SELECT * FROM SHASHI

When you run this script in Pubs database you will get the following message in Query Analyzer.

The Command(s) completed successfully.

Now you are ready to call/execute this procedure from Query Analyzer.

EXEC spGetShashi

This stored procedure creates a result set and returns to client.

You can call a stored procedure from within another stored procedure. You can even call a stored procedure from within itself. This technique is called a recursive call in programming. One of the advantages of using stored procedures is that application programmers and end users don't need to know the structure of the database or how to code SQL. Another advantage of it is they can restrict and control access to a database.

Classification of Stored Procedures

The classification of stored procedures is depends on the Where it is Stored. Based on this you can divide it in 4 sections.

  • System stored procedures
  • Local stored procedures
  • Temporary stored procedures
  • Extended stored procedures

System stored procedures are stored in the Master database and are typically named with a sp_ prefix. They can be used to perform variety of tasks to support SQL Server functions that support external application calls for data in the system tables, general system procedures for database administration, and security management functions.
For example, you can view the contents of the stored procedure by calling

sp_helptext [StoredProcedure_Name].

There are hundreds of system stored procedures included with SQL Server. For a complete list of system stored procedures, refer to "System Stored Procedures" in SQL Server Books Online.

Local stored procedures are usually stored in a user database and are typically designed to complete tasks in the database in which they reside. While coding these procedures don't use sp_ prefix to you stored procedure it will create a performance bottleneck. The reason is when you can any procedure that is prefixed with sp_ it will first look at in the mater database then comes to the user local database.

A temporary stored procedure is all most equivalent to a local stored procedure, but it exists only as long as SQL Server is running or until the connection that created it is not closed. The stored procedure is deleted at connection termination or at server shutdown. This is because temporary stored procedures are stored in the TempDB database. TempDB is re-created when the server is restarted.

There are three types of temporary stored procedures: local , global, and stored procedures created directly in TempDB.

A local temporary stored procedure always begins with #, and a global temporary stored procedure always begins with ##. The execution scope of a local temporary procedure is limited to the connection that created it. All users who have connections to the database, however, can see the stored procedure in Query Analyzer. There is no chance of name collision between other connections that are creating temporary stored procedures. To ensure uniqueness, SQL Server appends the name of a local temporary stored procedure with a series of underscore characters and a connection number unique to the connection. Privileges cannot be granted to other users for the local temporary stored procedure. When the connection that created the temporary stored procedure is closed, the procedure is deleted from TempDB.

Any connection to the database can execute a global temporary stored procedure. This type of procedure must have a unique name, because all connections can execute the procedure and, like all temporary stored procedures, it is created in TempDB. Permission to execute a global temporary stored procedure is automatically granted to the public role and cannot be changed. A global temporary stored procedure is almost as volatile as a local temporary stored procedure. This procedure type is removed when the connection used to create the procedure is closed and any connections currently executing the procedure have completed.

Temporary stored procedures created directly in TempDB are different than local and global temporary stored procedures in the following ways:

  • You can configure permissions for them.
  • They exist even after the connection used to create them is terminated.
  • They aren't removed until SQL Server is shut down.

Because this procedure type is created directly in TempDB, it is important to fully qualify the database objects referenced by Transact-SQL commands in the code. For example, you must reference the Authors table, which is owned by dbo in the Pubs database, as pubs.dbo.authors.

--create a local temporary stored procedure.

CREATE PROCEDURE #tempShashiAS
SELECT * from [pubs].[dbo].[shashi]

--create a global temporary stored procedure.

CREATE PROCEDURE ##tempShashi AS
SELECT * from [pubs].[dbo].[shasi]

-create a temporary stored procedure that is local to tempdb.

CREATE PROCEDURE directtempAS
SELECT * from [pubs].[dbo].[shashi]

An extended stored procedure uses an external program, compiled as a 32-bit dynamic link library (DLL), to expand the capabilities of a stored procedure. A number of system stored procedures are also classified as extended stored procedures. For example, the xp_sendmail program, which sends a message and a query result set attachment to the specified e-mail recipients, is both a system stored procedure and an extended stored procedure. Most extended stored procedures use the xp_ prefix as a naming convention. However, there are some extended stored procedures that use the sp_ prefix, and there are some system stored procedures that are not extended and use the xp_ prefix. Therefore, you cannot depend on naming conventions to identify system stored procedures and extended stored procedures.

Use the OBJECTPROPERTY function to determine whether a stored procedure is extended or not. OBJECTPROPERTY returns a value of 1 for IsExtendedProc, indicating an extended stored procedure, or returns a value of 0, indicating a stored procedure that is not extended.

USE MasterSELECT OBJECTPROPERTY(object_id('xp_sendmail'), 'IsExtendedProc')

Create a Stored Procedure 

CREATE PROCEDURE SQL statement is used to create an SP. When the CREATE PROCEDURE statement is executed, the syntax of the SQL statements within the procedure is checked. If you have made a coding error the system responds with an appropriate message and the procedure is not created.

The Syntax of the CREATE PROCEDURE statement


CREATE {PROC|PROCEDURE} Procedure_name
[Parameter_declaration]
[WITH {RECOMPILE|ENCRYPTION|RECOMPILE, ENCRYPTION}]
AS sql_statements


You can use CREATE PROCEDURE statement to create a stored procedure in the database. The name of the stored procedure can be up to 128 characters and is typically prefixed with the letters sp.

If you look at the above options like AS, RECOMPILE, ENCRYPTION these are having some significance meaning to it.

The AS clause contains the SQL statements to be executed by the stored procedure. Since a stored procedure must consist of single batch.

Recompile is used when you want to compile the stored procedure every time when you call. This comes into the picture when one doesn’t want to catch the execution plan of stored procedure in the database. Encryption implies that you want to hide this code so that no one can see it. This is very important when you want to distribute the code across the globe or when you want to sell this code to other vendors. But make sure you have original copy it; because once you encrypted it no one can decrypt it.

Apart from the stored procedure that store in the database a permanent entity you can create stored procedure as per you session. That means as long the as the session is alive then the stored procedure is available in the memory means in the database.
Once the session ends the stored procedure is vanished this actually depends on what type of stored procedure you have chosen to create it.

Stored procedure provide for two different types of parameters: input parameters and Output Parameters. An input Parameter is passed to the stored procedure from the calling program. An output parameter is returned to the calling program from the stored procedure. You can identify an output parameter with the OUTPUT keyword. If this keyword is omitted the parameter is assumed to be an input parameter.

You can declare an input parameter so that it requires a value or so that its value is optional. The value of a required parameter must be passed to the stored procedure from the calling program on an error occurs. The value of an optional parameter doesn’t need to be passed from the calling program. You identify an optional parameter by assigning a default value to it. Then if a value isn’t passed from the calling program, the default value is used. You can also use output parameter as input parameters. That is you can pass a value from the calling program to the stored procedure through an output parameter. However is not advisable to pass parameters to Output parameters.

The syntax for declaring the parameters

@Parameter_name_1 data_type [= default] [OUTPUT]
[, @Parameter_name_2 data_type [= default] [OUTPUT]


Parameter declarations:
@FirstName varchar(50) -- Input parameter that accepts a string.
@LastName varchar(50) -- Output Parameter that returns a string.

Create Procedure statement that uses an input and an output parameter.

CREATE PROC spGetShashi
                       @FirstName varchar(50),
                       @LastName varchar(50)
AS
SELECT  @LastName= ln_Name
FROM    SHASHI
WHERE   fn_name = @FirstName


Create procedure statement that uses an optional parameter.

CREATE PROC spGetShashi
                       @LastName varchar(50),
                       @FirstName varchar(50) = 'shashi'
AS
SELECT  @LastName= ln_Name
FROM    SHASHI
WHERE   fn_name = @FirstName


A stored procedure can declare up to 2100 parameters. If you declare two or more parameters, the declarations must be separated by commas.

Delete or Update a Stored Procedure

You use DROP PROC SQL statement to delete one or more stored procedures from database. To update the stored procedure you use ALTER PROC SQL statement.

The syntax of the DROP PROC statement

DROP {PROC|PROCEDURE} Procedure_name [, ]

The syntax of the ALTER PROC statement

ALTER {PROC|PROCEDURE} Procedure_name[Parameter_declaration][WITH {RECOMPILE|ENCRYPTION|RECOMPILE, ENCRYPTION}]AS sql_statements

When you delete a procedure any security permission that are assigned to the procedure are also deleted. In that case you will want to use the ALTER PROC statement to modify the procedure and preserve permissions.

Calling stored procedure with Parameters

To pass parameter values to a stored procedure, you code the values in the EXEC statement after the procedure name. You can pass the parameters either by position or by name.

Passing parameters by Name:

Write the following code in Query Analyzer

DECLARE @LN VARCHAR(100)EXEC spGetShashi @FirstName = 'shashi', @LastName = @LN OUTPUT

Passing parameters by Position:

DECLARE @LN VARCHAR(100)EXEC spGetShashi @LN OUTPUT, 'shahsi'

In fact you can use both notations to pass parameters to stored procedures when you are calling. To pass parameters by position, list them in the same order as they appear in the CREATE PROCEDURE statement and separate them with commas. When you use this technique, you can omit optional parameters only if they are declared after any required parameters.

To use an output parameter in the calling program, you must declare a variable to store its value. Then you use the name of the variable in the EXEC statement and you code the OUTPUT keyword after it to identify it as an output parameter.

Handling error in stored procedure

In addition to passing output parameters back to the calling program, stored procedures also pass back a return value. By default, this value is zero. If an error occurs during the execution of a stored procedure you may want to pass a value back to the calling environment that indicates the error that occurred. To do that you use the RETURN statement and the @@ERROR function.

The @@ERROR system function returns the error number that's generated by the execution of the most recent SQL statement. If the value is zero, it means that no error has occurred. The stored procedure listed below uses this function to test whether a DELETE statement that deletes a row from authors table is successful.

CREATE PROC spDeleteShashi @FirstName varchar(50) AS
DECLARE @ErrorVar int
DELETE FROM SHASHI WHERE fn_name = @FirstName
SET @ErrorVar = @ERRORIF @ErrorVar <> 0        
BEGIN              
   PRINT 'An Unknown Error Occurred'             
   RETURN @ErrorVar       
END

The RETURN statement immediately exists the procedure and returns an optional integer value to the calling environment. If you don't specify the value in this statement the return value is zero.

Stored Procedures part 2

In this article I will explain you about stored procedure.
How to create, execute and alter stored procedure.
Why to use stored procedures and advantages of stored procedures. 


  • A stored procedure is a group of Transact-SQL statements compiled into a single execution plan.
  • Stored Procedures are coding block in database server. It is pre compiled entity i.e. it is compiled at once and can be used again and again.
  • With help of stored procedure a group of SQL statements can be executed sequentially.
  • To supply data to the procedure we must have to use parameters in procedure.
  • Stored procedures use parameters mapping concept.
  • In parameter mapping front end and procedure parameters names, type and direction must be same and where front-end parameter length should be less than or equal to procedure parameter length (than only can map parameters).
  • To return any value from procedure we use return statement.

How to create a stored procedure

 
 

create
procedure insertData


(@RollNo int,

@Name varchar(50),

@Fees float)

 
 

as

begin

insert
into student values(@RollNo,@Name,@Fees)


select
*
from student


end

 
 

How to execute a stored procedure

 
 

exec insertData 8,
'Mahesh', 5600


 
 

Output of above stored procedure


 



 

Modifying a Stored Procedure

 
 

alter
procedure insertData


(@RollNo int,

@Name varchar(50),

@Fees float)

 
 

as

begin

insert
into student values(@RollNo,@Name,@Fees)


select
*
from student


end

 
 


 

Why to use stored procedures?

 
 

You normally write SQL statements, like select, inserts, updates to access your data from database. If you find yourself using the same query over and over again, it would make sense to put it into a stored procedure.

 
 

Every time you write a query it is parsed in database. If you have written a stored procedure for it, it will be parsed once and can be executed N number of times.

 
 

Stored procedures can also improve performance. All the conditional logic and is written into a stored procedure which is a single execution block on the database server.

 
 

Advantages of stored procedure

 
 

Modular programming

Stored Procedures are coding block in database server. IT is pre compiled entity i.e. it is compiled at once and can be used again and again.

Performance

Stored procedures provide faster code execution and reduce network traffic.

 
 

Faster execution: Stored procedures are parsed and optimized as soon as they are created and the stored procedure is stored in memory. This means that it will execute a lot faster than sending many lines of SQL code from your application to the SQL Server. Doing that requires SQL Server to compile and optimize your SQL code every time it runs.

 
 

Reduced network traffic: If you send many lines of SQL code over the network to your SQL Server, this will impact on network performance. This is especially true if you have hundreds of lines of SQL code and/or you have lots of activity on your application. Running the code on the SQL Server (as a stored procedure) eliminates the need to send this code over the network. The only network traffic will be the parameters supplied and the results of any query.

Security

Users can execute a stored procedure without needing to execute any of the statements directly.

 
 

Stored procedure can provide advanced database functionality for users who wouldn't normally have access to these tasks, but this functionality is made available in a tightly controlled way.

 
 

Conclusion

 
 

Hope this article might have helped you in understanding stored procedures.

 
 

Your feedback and constructive contributions are welcome. Please feel free to contact me for feedback or comments you may have about this article.

Tuesday, July 20, 2010

No more SSP’s in Sharepoint 2010

In SharePoint 2010 Shared Service Providers (SSP's) are replaced by Service Applications. Services are no longer combined into a SSP. Services are running independent as a service application.
 

Why not SSP??

SSPs were pretty handy in Office SharePoint Server 2007. They allowed us to create a configuration of profiles, audiences, Excel Services, BDC and search that we could share between two Web applications. But what if we wanted one Web application to simply use the same search configuration in one SSP but have a totally different profile / BDC configuration? The only option was to create a new SSP and duplicate the search. But these two SSPs were totally independent.

Another trick was the scalability of SSPs. Nor was it easy to share an SSP across SharePoint farms.

 
 

Here comes the Service Applications.

Microsoft took a sledge hammer to the SSP architecture and broke it into pieces. Think of service applications as little programs, but don't think in terms of an individual EXE or DLL. Instead, think of it more like a complete application that may be comprised of multiple assemblies, databases, timer jobs, Win32 services, external systems, etc.




From the above diagram, you can see many of the benefits the new Service Model provides. Some of them I have mentioned below

  • A more effective targeting of services to the Web apps you've created (Web apps consume services on an individual basis)
  • Each Web app can use any combination of the available Service Apps
  • You can deploy multiple instances of the same Service Apps – giving each one a unique name
  • This model also allows Cross-Farm Service Apps
  • You can also write your own services that take advantage of the SharePoint infrastructure!

 
 

With this new Service model, comes some new terms

  • Service: A set of bits installed on a SharePoint 2010 farm that's capable of providing some functionality
  • Service Application: A specific farm-level configuration of the Service in SharePoint. For example, the specific configuration of Office Web apps Service in your new
    SharePoint 2010 farm.
  • Service Machine Instance: A machine-level instance of the Service running on an app server
  • Service App Proxy: A pointer to a Service App that exists on the WFE
  • Service Consumer: A SharePoint feature, such as a web-part, that talks with the service and makes its functionality available to an end user

 
 

What Service apps are NEW and what actually they do?

You've seen from the above that the architecture has been modified and they are lots of NEW Services available in SharePoint 2010. I've provided a brief list of some of the new Services and what they do below:

  • Access Services – Allows viewing, editing, and interacting with Access databases in a browser.
  • Managed Metadata Service – Provides access to managed taxonomy hierarchies, keywords, social tags and Content Type publishing across site collections.
  • Secure Store Service –Provides capability to store data (e.g. credential set) securely and associate it to a specific identity or group of identities.
  • State Service – Provides temporary storage of user session data for Office SharePoint Server components.
  • Usage and Health data collection – This service collects farm wide usage and health data and provides the ability to view various usage and health reports.
  • Visio Graphics Service – Enables viewing and refreshing of published Visio diagrams in a web browser.
  • Web Analytics Service Application – Enable rich insights into web usage patterns by processing and analyzing web analytics data .
  • Word Conversion Service Application – Provides a framework for performing automated document conversions

Thursday, June 17, 2010

Print, Chart, Slide Show, Color Calender

Wednesday, May 19, 2010

Monitoring SharePoint Usage through an ASP.NET Web Application

Introduction

It is a common requirement to gather information around the Windows SharePoint site usage. Organizations prefer to find out the popular sites in their organizations are or what external WSS sites attract the most number of visitors. This will provide information necessary for an organization to identify the important sites in their environment and properly manage them with extra resources if necessary.

One of the common complains around accessing theses data are the inflexibility of gathering information in a central location. The administrator will have to navigate to the selected SharePoint site administration pages to access the data. This will become a more time consuming exercise when the administrator need to collect usage data from larger number of SharePoint sites.

In this article, I am looking at creating an ASP.NET web application that will populate a collection of SharePoint sites in a drop down list for a given SharePoint site collection. The web application will display the usage details of the selected SharePoint site from the list. This will help the SharePoint administrator to gather all SharePoint usage data from a central location with out have to navigate many different SharePoint site locations.

Usage Analysis Data Web Report

Figure 1 display a Usage Analysis data for a Windows SharePoint site. The users have the option of selecting a monthly or a daily report.


Figure 1: Monthly Usage Analysis Report

Usage Analysis Processing Reports

First of all let's have a look at what is Usage Analysis Reports in SharePoint. Theses reports will help the organizations to determine how the web sites are used in their environment. The data is taken from IIS Logs on the front end web servers and stored in to temporary files. The data is merged in to the content database on the back end SQL Servers when the daily log processing takes place.

The Usage Analysis is not enabled by default when the organization deploys the Windows SharePoint Services Sites. Organizations should enable the Usage Analysis logging process on the servers when they require gathering usage information. The logs files are created daily and a flag is attached to mark that it has been processed.

These logs files are not automatically deleted, they are preserved in "local_drive (C) :\Windows\system32\LogFiles\W3SVC*" where * indicates the Internet Information Server (IIS) instance number of the virtual server as displayed in Figure2. Organizations should consider the advantages against the disk space storage before enabling the Usage Analysis service in their environment. The organization can stop logging process' any time they require to do so.


Figure 2: Preserved log files folder structure with W3SVC* format

By default the log files are located at "local_drive (C) :\Windows\system32\LogFiles\STS" directory. Separate folders are created under above directory for each virtual server and separate folders for each day as displayed in the Figure 3.


Figure 3: Separate directories for each virtual server and for each day

Organizations can configure the above Log file store path for their own preferred path and create up to 30 log files. (Please look at Setting up Usage Analysis process for more details.) If an organization decides to store the log files in their preferred location, they should grant Read, Write and Update rights permissions for STS_WPG user group for the specified folder. Without the permissions, the usage log files cannot be created or updated by IIS.

Setting up Usage Analysis Processing

Administrators can control the setting of Usage Analysis process using the SharePoint Central Administration page. The user must be an administrator on the local server or a member of the SharePoint Administrators group to configure the analysis processing. If the organization adds a new virtual server after the analysis service been configured, they will need to reconfigure the analysis service to collect the data on the newly added virtual server.

View Usage Analysis Reports

The user must be an administrator or have the View Usage Data right for a site to view the site usage reports. The reports are available through Site Administration page.

The usage data is collected and stored for the entire site collection on a server at a time. The users can see the total number of hits for a site collection on the Site Collection Usage Summary page and for more detailed information, Site Usage Report page for individual sites or sub sites usage information.

View Site Usage Report

Site usage reports are useful for identifying which content on Windows SharePoint Services sites are being heavily used or used very little. This will help organizations to understand which sites are candidates for archiving and which sites should be kept online. In addition, this report contains information regarding how much storage space WSS sites are using. This page provides a report that contains following information:


Figure 9: Different reports available

The users can select a report option and a daily or monthly option to generate a report. Figure 9 displays a monthly report of all the pages accessed and different kind of reports options available.

Code Example

The web page contains a text box to enter the SharePoint site collection URL. The appropriate sub site will be listed in a dropdown list when user clicks the Submit button. The user then have the option of viewing the daily or monthly usage report of a selected site.

First of all you will need to add the Microsoft.SharePoint.dll to your web application reference list. This will give us the access to the SharePoint Object Model.

Then instantiate the SPSite object as displayed below. The absolute URL is passed in through the txtWSSSiteUrl text box. This will populate site collection for the given URL.

//Get the site collection
SPSite mySiteCollection = new SPSite(txtWSSSiteUrl.Text);

Then to access an individual site, instantiate the SPWeb object as displayed below. I am passing in the site name as a parameter.

//Get the details of the selected WSS site
SPWeb site = mySiteCollection.AllWebs[siteName];

After constructing the site SPWeb object, developers can access the information of the site usage data using the public method "GetUsageData" of the SPWeb object as displayed in code example.

GetUsageData(Microsoft.SharePoint.Administration.SPUsageReportType, Microsoft.SharePoint.Administration.SPUsagePeriodType) Method.

The GetUsageData method of the SPWeb class returns a data table that contains information about the usage of a Web site based on the specified type of report and time interval.

SPUsageReportType Enumeration

The SPUsageReportType enumeration specifies the type of information returned in a usage report for a SharePoint site.

The following table shows the members of the SPUsageReportType enumeration and a brief description

Name

Description

browser

The type of Web browser used to visit the SharePoint site. All usage data refers specifically to visits from referring URLs external to the site.

os

The operating system used on the client computer. All usage data refers specifically to visits from referring URLs external to the site.

refUr

External URLs through which users navigated to the SharePoint site.

url

URLs of pages that are visited or of pages for lists that are updated. Discussions about a page are counted as hits on that page.

user

Users who visited the site.

SPUsagePeriodType Enumeration

The SPUsagePeriodType enumeration specifies the time interval on which a usage report for a Web site is based.

The following table shows the members of the SPUsagePeriodType enumeration and a brief description

Name

Description

day

Returns usage information for each day during the past 31 days starting from the previous day

lastMonth

Summarizes usage information for the last 31 days relative to the previous day

I am binding the data table return from GetUsageData property to a DataGrid control to display the information.

Accessing User daily report

//Users who visited the site
DGUsers.DataSource = site.GetUsageData(SPUsageReportType.user, SPUsagePeriodType.day);

Accessing User monthly report

//Users who visited the site
DGUsers.DataSource = site.GetUsageData(SPUsageReportType.user, SPUsagePeriodType.lastMonth);

Accessing Browser daily report

//The type of browsers used to visit the site
DGBrowser.DataSource = site.GetUsageData(SPUsageReportType.browser, SPUsagePeriodType.day);

Accessing Browser monthly report

//The type of browsers used to visit the site
DGBrowser.DataSource = site.GetUsageData(SPUsageReportType.browser, SPUsagePeriodType.lastMonth);

Accessing Operating System daily report

//The Operating System used in client computer
DGOs.DataSource = site.GetUsageData(SPUsageReportType.os, SPUsagePeriodType.day);

Accessing Operating System monthly report

//The Operating System used in client computer
DGOs.DataSource = site.GetUsageData(SPUsageReportType.os, SPUsagePeriodType.lastMonth);

Accessing refUrl daily report

//External URL client used to navigate to SharePoint site
DGRefUrl.DataSource = site.GetUsageData(SPUsageReportType.refUrl, SPUsagePeriodType.day);

Accessing refUrl monthly report

//External URL client used to navigate to SharePoint site
DGRefUrl.DataSource = site.GetUsageData(SPUsageReportType.refUrl, SPUsagePeriodType.lastMonth);

Accessing url daily report

//URL's of pages visited
DGUrls.DataSource = site.GetUsageData(SPUsageReportType.url, SPUsagePeriodType.day);

Accessing url monthly report

//URL's of pages visited
DGUrls.DataSource = site.GetUsageData(SPUsageReportType.url, SPUsagePeriodType.lastMonth);

Deploying the Web Application to the SharePoint Portal Server


Figure 10: A list of sub sites of the site collection


Figure 11: Daily Usage Analysis Report of a Windows SharePoint Site

Conclusion

SharePoint Administrators should be able to use this article as a starting point and develop their SharePoint Usage Analysis data gatherer web application according to their requirements.

Update SharePoint UserInfo List with More Active Directory Info

Introduction

A little while back, I downloaded a Web Part that was supposed to show the current user's weather. It was coded to query the SiteUserInfoList and pull back the user's WorkCity, WorkState, and WorkCountry properties so that it could correctly locate the user. I installed the Web Part and found that it didn't work. Those properties are in Moss' User Profile but not in the Site collection's SiteUserInfoList. The person who coded the Web Part obviously didn't like to do testing. So, what was I to do? I didn't want to resort to Moss' User Profile because I want all my Web Parts to work for non-Moss implementations. So, I decided to just write a job that would run every night to update the SiteUserInfoList with more Active Directory properties.

Also, are you tired of getting "User does not exist or is not unique" errors when adding users to groups? Well, this code will also update the title of every user that is missing in Active Diretory to "XX - <previousTitle>". This is an easy way to expose to you that the user is missing in Active Directory so that when you are using the User Selector dialog, you can prevent yourself from getting that error.


Installation

First, copy the build directory to the desktop of each server in your farm. Run "Install AD Updator.bat" as Administrator. Type in the name of your Web Application you want to install to, click Enter. Make sure you only run this on one server at a time.

The Code

The code runs through all the users in SharePoint and then pulls their information from Active Directory. It then takes the info from Active Directory and updates specific fields like Title, Phone, and etc. Then, it stores the rest of the info (WorkCity, WorkZip, and etc.) in the property bag of the user's UserInfo item.

Collapse Copy Code

using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.SharePoint.Administration;

using Microsoft.SharePoint;

using System.Diagnostics;

using Microsoft.SharePoint.Utilities;

using System.DirectoryServices;

using System.DirectoryServices.ActiveDirectory;

using System.Security.Principal;

namespace Mullivan.SharePoint.Jobs

{

public class AdUserInfoUpdateJobDefinition : SPJobDefinition

{

internal const string _JOBNAME = "AD User Info Update Job";

public AdUserInfoUpdateJobDefinition () : base() { }

public AdUserInfoUpdateJobDefinition(SPWebApplication webApp)

: base(_JOBNAME, webApp, null, SPJobLockType.Job)

{

this.Title = _JOBNAME;

}

public override void Execute(Guid targetInstanceId)

{

try

{

DirectoryEntry domain = GetDomainEntry();

if (domain == null)

throw new Exception("Domain not found.");

foreach (SPSite site in this.WebApplication.Sites)

{

using (SPWeb web = site.RootWeb)

{

SPListItemCollection userItems = web.SiteUserInfoList.Items;

for (int i = 0; i < userItems.Count; i++)

{

try

{

double progress = ((double)(i + 1)) /

(double)userItems.Count;

UpdateProgress(Convert.ToInt32(progress * 100));

SPListItem userItem = userItems[i];


 

SPUser user = web.SiteUsers.GetByID(userItem.ID);

if (user == null)

throw new Exception(string.Format(

"User account {0} not found in site {1}.",

userItem.Name, site.Url));

DateTime dtUserItemUpdated =

(DateTime)userItem["Modified"];

if (IsPerson(userItem) && !IsSystem(user))

{

AdUserInfo userInfo = GetUserInfo(user, domain);

if (userInfo == null || !userInfo.IsActive)

{

string jobTitle = (string)userItem["JobTitle"];

if (string.IsNullOrEmpty(jobTitle))

jobTitle = string.Empty;

if (!jobTitle.StartsWith("XX - "))

{

jobTitle = string.Format("XX - {0}", jobTitle);

userItem["JobTitle"] = jobTitle;

userItem.Update();

}

}

else

{

object updateFlag =

userItem.Properties["AdUpdateFlag"];

if (userInfo.LastModified > dtUserItemUpdated

|| updateFlag == null)

{

userItem.Properties["AdUpdateFlag"] = 1;

if (userInfo.Email != null)

{

userItem["EMail"] = userInfo.Email;

user.Email = userInfo.Email;

}

if (userInfo.Department != null)

userItem["Department"] = userInfo.Department;

if (userInfo.JobTitle != null)

userItem["JobTitle"] = userInfo.JobTitle;

else

{

string val = (string)userItem["JobTitle"];

if (val != null)

{

if (val.StartsWith("XX - "))

userItem["JobTitle"] =

val.Substring(5, val.Length - 5);

}

}

if (userInfo.FirstName != null)

userItem["FirstName"] = userInfo.FirstName;

if (userInfo.LastName != null)

userItem["LastName"] = userInfo.LastName;

if (userInfo.WorkPhone != null)

userItem["WorkPhone"] = userInfo.WorkPhone;

if (userInfo.Office != null)

userItem["Office"] = userInfo.Office;

if (userInfo.WorkZip != null)

userItem.Properties["WorkZip"] =

userInfo.WorkZip;

if (userInfo.WorkCity != null)

userItem.Properties["WorkCity"] =

userInfo.WorkCity;

if (userInfo.WorkState != null)

userItem.Properties["WorkState"] =

userInfo.WorkState;

if (userInfo.WorkCountry != null)

userItem.Properties["WorkCountry"] =

userInfo.WorkCountry;

userItem.Update();

user.Update();

}

}

}

}

catch (Exception ex)

{

Logging.ServiceLog.LogException(_JOBNAME, ex);

}

}

web.Dispose();

}

site.Dispose();

}

}

catch (Exception ex)

{

Logging.ServiceLog.LogException(_JOBNAME, ex);

}

}

private bool IsSystem(SPUser user)

{

if (user.ID.Equals(1073741823))

return true;

if (user.LoginName == null)

return true;

if(user.LoginName.ToLower().StartsWith("nt authority"))

return true;

if (user.LoginName.ToLower().StartsWith("system"))

return true;

return false;

}

private AdUserInfo GetUserInfo(SPUser user, DirectoryEntry domain)

{

string id = user.Sid;

bool localMachine = domain.Path.StartsWith("WinNT");

string userFlagProperty = "userAccountControl";

if (localMachine)

userFlagProperty = "UserFlags";

DirectoryEntry deUser = FindUser(id, domain);

if (deUser != null)

{

AdUserInfo adUserInfo = new AdUserInfo();

adUserInfo.IsActive = true;

if (localMachine)

{

//For testing purposes... Production Environment should be using

// Active Directory

adUserInfo.LastModified = DateTime.Now;

string value = GetValue("FullName", deUser);

if (!string.IsNullOrEmpty(value))

{

string[] vals = value.Split(new char[1] { ' ' }

, StringSplitOptions.RemoveEmptyEntries);

if (vals.Length > 0)

adUserInfo.FirstName = vals[0];

if (vals.Length > 1)

adUserInfo.LastName = vals[vals.Length - 1];

}

adUserInfo.WorkCity = "St Louis";

adUserInfo.WorkState = "MO";

adUserInfo.WorkZip = "63141";


 

}

else

{

DateTime dtModified = DateTime.Now;

if (DateTime.TryParse(GetValue("whenChanged", deUser),

out dtModified))

adUserInfo.LastModified = dtModified;

else

adUserInfo.LastModified = DateTime.Now;

adUserInfo.LastName = GetValue("sn", deUser);

adUserInfo.FirstName = GetValue("givenName", deUser);

adUserInfo.Name = GetValue("sAMAccountName", deUser);

adUserInfo.Office = GetValue("physicalDeliveryOfficeName", deUser);

adUserInfo.WorkPhone = GetValue("telephoneNumber", deUser);

adUserInfo.Department = GetValue("department", deUser);

adUserInfo.Email = GetValue("mail", deUser);

adUserInfo.JobTitle = GetValue("title", deUser);

adUserInfo.WorkCity = GetValue("l", deUser);

adUserInfo.WorkState = GetValue("st", deUser);

adUserInfo.WorkCountry = GetValue("c", deUser);

adUserInfo.WorkZip = GetValue("postalCode", deUser);

}

string userAC = GetValue(userFlagProperty, deUser);

int userValue = 0;

if(int.TryParse(userAC, out userValue))

{

try

{

AdUserAccountControl userAccountControl =

(AdUserAccountControl)userValue;

adUserInfo.IsActive =

//Make sure it's not disabled

((userAccountControl & AdUserAccountControl.ACCOUNTDISABLE)

!= AdUserAccountControl.ACCOUNTDISABLE)

//Make sure it's a normal account

&& ((userAccountControl &

AdUserAccountControl.NORMAL_ACCOUNT) ==

AdUserAccountControl.NORMAL_ACCOUNT);

}

catch (Exception ex)

{

Logging.ServiceLog.LogException(_JOBNAME, ex);

}

}

return adUserInfo;

}

else

return null;

}

private string GetValue(string propertyName, DirectoryEntry deUser)

{

if (deUser.Properties.Contains(propertyName))

{

PropertyValueCollection pvc = deUser.Properties[propertyName];

if (pvc.Count > 0)

{

object objValue = pvc[0];

if (objValue != null)

return objValue.ToString();

}

}

return null;

}

private DirectoryEntry FindUser(string id, DirectoryEntry domain)

{

if (!domain.Path.StartsWith("WinNT"))

{

DirectorySearcher search = new DirectorySearcher(domain);

search.Filter =

string.Format("(&(objectClass=person)(objectSid={0}))", id);

SearchResult result = search.FindOne();

if(result != null)

return result.GetDirectoryEntry();

}

else

{

foreach (DirectoryEntry de in domain.Children)

{

SecurityIdentifier si = new SecurityIdentifier(

(byte[])de.Properties["objectSid"][0], 0);

if (string.Compare(si.Value, id, true) == 0)

return de;

}

}

return null;

}

private DirectoryEntry GetDomainEntry()

{

try

{

return Domain.GetComputerDomain().GetDirectoryEntry();

}

catch(Exception ex)

{

Logging.ServiceLog.LogException(_JOBNAME, ex);

#if SULLYSERVER

DirectoryEntry localMachine = new DirectoryEntry(

string.Format("WinNT://{0},Computer", Environment.MachineName));

return localMachine;

#else

return null;

#endif

}

}

private bool IsPerson(SPListItem userItem)

{

string contentType = userItem.ContentType.Name;

if (!contentType.Equals("Person"))

return false;

return true;

}

private void Trace(string message)

{

System.Diagnostics.Trace.WriteLine(message, _JOBNAME);

}

}

}

We can now pull this information out and use it in our Web Parts by doing the following (this code is an example taken from the WeatherWebPart that I modified):

Collapse Copy Code

private bool SetUserLocation()

{

try

{

SPWeb web = SPContext.Current.Web;

SPUser u = web.SiteUsers[web.CurrentUser.LoginName];

SPList userList = web.SiteUserInfoList;

SPListItem uItem = userList.Items.GetItemById(u.ID);


 

if (uItem != null)

{

string strZip = uItem.Properties["WorkZip"] as string;

if (!string.IsNullOrEmpty(strZip))

this.Zip = strZip;

return true;

}

}

catch

{

this.Zip = DEFAULT_ZIP;

}

return false;

}