Showing posts with label Best Practice. Show all posts
Showing posts with label Best Practice. Show all posts

Friday, October 23, 2009

Adding a list item more efficiently

Scenario:
For one of our requirement we were suppose to add 100s of item to multiple lists and we got into some performance issues.

Solution:
Here's a workaround to avoid the overhead of calling SPList.Items.Add() method.

SPList.Update() must be called to save the newly created item.

Code:

public static SPListItem AddItem(this SPList list){

SPQuery query = new SPQuery()
{
Query = "<Where><Eq><FieldRef Name=\"ID\"/><Value Type=\"Integer\">-1</Value></Eq></Where>",
ViewFields = "<FieldRef Name=\"ID\"/>"
};
return list.GetItems(query).Add();
}

Friday, September 4, 2009

Deployment command issues

Scenario:
This is one of the common issues I have seen with people developing solution on single WFE server farm and deploying sharepoint solution to multi-server WFE farm.

"The solution has not been deployed and may require clean up"

Reason:
Though there can be several issues, I am pointing out few here.

1. STSADM -o execadmsvcjobs
Often this command is used after retract solution and deploy solution command. This command executes all administrative timer jobs immediately instead of waiting for the timer job to run. Think of it as a console application with the same code as of Timer Job, only thing is it will run instantly. So far so good. But assuming that this means it has executed the job on all server is not true, which can be very problematic in multi-server farm.

Common Error: The solution-deployment-trainingwebparts.wsp-0 job completed successfully, but could not be properly cleaned up. This job may execute again on this server.

Recommendation : Wait for timer job to execute the deployment/retracting jobs and not to use it at all in deployment /retracting scripts in multi-server farm.

2. IISReset / Application Pool Reset
This command basically restarts the IIS services which is required to make sure web.config / GAC and other XML file based changes done on the file system get picked up.

Recommendation : Make sure you reset IIS / Application pool on all the WFEs

3. Resetting Timer service
net stop "Windows Sharepoint Services Timer"
net start "Windows Sharepoint Services Timer"

This command basically restarts the Timer services, which is required to make sure it picks up the code changes done to Custom Timer Job.

Recommendation : Make sure you reset Timer job on all the WFEs

4.Feature Activation:
Try to keep these commands in separate file or add 30sec pause between deploy solution and feature activation , other you might get error complaining feature is not installed ( on another server ).

Recommendation : Use separate file for these kind of commands.

5.Use of Force attribute:
Lot of times we use Force attribute as a rule of thumb.. :-) , try to understand the need of this attribute.

As per MSDN , using it in UninstallFeature forces an installation of a feature that is already installed and in ActivateFeature it activates a feature. This causes any custom code associated with the feature to rerun.

Recommendation : Try to avoid the use of force attribute and only use it when retracting is not able to clean up the features.

5.Use of AllContentUrls attribute:
You may not have used it directly but if you remember the drop down saying deploy on All Web Applications ? , that what it is.

Don't use this.

Recommendation : Deploying the solution to each of the web application. If you have a lot of Web Applications then you can script it.

Tuesday, July 28, 2009

SPQuery Few important things

1. Always specify the RowLimit to get limited results.

oQuery.RowLimit = 100;
2. To Get the Search Items from the sub folders of the list using SPQuery you can do following. Check here
SPQuery.ViewAttributes = "Scope='Recursive'";
or
SPQuery.ViewAttributes = "Scope='RecursiveAll'";
3. Be sure to create a new SPQuery instance each time you use it. You cannot create one SPQuery instance and then reuse it multiple times in a loop where you alter the SPQuery's Query value.
 for (int i = 0; i < 10 ; i++)
{
SPQuery oQuery = new SPQuery();
oQuery.Query = "<Where><Eq><FieldRef Name='AssignedTo' /><Value Type='UserMulti'>"+i +"</Value></Eq></Where>";
SPListItemCollection collListItems = list.GetItems(oQuery);
}
4. SPQuery query object doesn't need to include tags
oQuery.Query = "Completed";
5. If you want to do CAML query which also consider the time in datetime fields then try this
<Where><Eq><FieldRef Name='Created'/><Value Type='DateTime' IncludeTimeValue='TRUE'><Today /></Value></Eq></Where>
6. SPQuery can't be used to search across site collection.One can use SPSiteDataQuery class to search across multiple Lists.

To query the lookup based value items
<where><eq><fieldref name="Employee" lookupid="TRUE"><value type="User">1</value></eq></where>  
7. To restrict the items to approved, use moderationtype attribute. more details here
SPQuery.ViewAttributes = "Scope='Recursive' ModerationType='HideUnapproved'";
8. If you want your query to return empty columns, you have to add Nullable='TRUE' to the viewfields.
query.ViewFields="<FieldRef Name='Description' Nullable='TRUE'/>";
To get the item related within past few days , you can use OffsetDays attribute along with Today.
<Where><Eq><FieldRef Name='Created'/><Value Type='DateTime' ><Today OffsetDays='-7' /></Value></Eq></Where>
Article:
SPQuery Best Practice

Saturday, July 4, 2009

CAT.NET for Code Analysis

Tool:
This is another one , I use for Code Analysis. Infact this tool is FxCop but with a new name and rules.

You can download CTP from here -- > Download 32 bit MSI
If you check the links below, you can also find the 64bit edition.

How to Use:
This tool is preety simple to use as it automatically get integrated with Visual Studio. If you have Visual Studio then you need to re-open the project.

Steps:
1. You can run it from Tools > CAT.Net Code Analysis , a new window will open.
2. Configure the default settings for location of your Code Analysis reports.
3. You can click to Analyze to start analyzing the binaries.

Wednesday, July 1, 2009

Using FxCop for Code Analysis the easy way

Scenario:
I keep looking for ways to provide tools to easily discover common issues so that automatically code can comply with best practice.

You can bing about Best Practice for Code Analysis and there is a utility which can help you to find some of the common problems. You can download it from here -- > Download MSI

Solution:
As I said tools should be easy to use , so here a small tip to make FxCop part of you every Visual Studio project.

FxCop

Steps:
1. Install FxCop 1.35 locally.
2. Open Visual Studio
3. Go to Tools > External Tools > Add a new tool with below settings

Setting:


Title : FxCopCmd

Path : C:\Program Files\Microsoft FxCop 1.35\FxCopCmd.exe ( This is default location where FxCop is installed, so if u have choose a different location while installing it, make sure to point it to right spot. )

Arguments : /c /searchgac /f:$(BinDir)$(TargetName)$(TargetExt)

Use Output Window : Checked
Now just go to Tools > FxCopCmd and you can see the report in your output window.

Sunday, June 21, 2009

Exception Handling in WCF

Scenario:
Robust exception handling in key to any good system , specially with a new technology when you have lot of unknowns. WCF is easy to adopt but without a robust error handling its hard to debug in an environment where you have limited control.

Solution:
Here's a sample from MSDN , but important thing to note is the sequence in which exceptions are handled. Most specific once first and then the generic once.

Code:

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Microsoft.WCF.Documentation;

public class Client
{
public static void Main()
{
// Picks up configuration from the configuration file.
SampleServiceClient wcfClient = new SampleServiceClient();
try
{
// Making calls.
Console.WriteLine("Enter the greeting to send: ");
string greeting = Console.ReadLine();
Console.WriteLine("The service responded: " + wcfClient.SampleMethod(greeting));
Console.WriteLine("Press ENTER to exit:");
Console.ReadLine();
}
catch (TimeoutException timeProblem)
{
Console.WriteLine("The service operation timed out. " + timeProblem.Message);
wcfClient.Abort();
Console.ReadLine();
}
// Catch the contractually specified SOAP fault raised here as an exception.
catch (FaultException<GreetingFault> greetingFault)
{
Console.WriteLine(greetingFault.Detail.Message);
Console.Read();
wcfClient.Abort();
}
// Catch unrecognized faults. This handler receives exceptions thrown by WCF
// services when ServiceDebugBehavior.IncludeExceptionDetailInFaults
// is set to true.
catch (FaultException faultEx)
{
Console.WriteLine("An unknown exception was received. "
+ faultEx.Message
+ faultEx.StackTrace
);
Console.Read();
wcfClient.Abort();
}
// Standard communication fault handler.
catch (CommunicationException commProblem)
{
Console.WriteLine("There was a communication problem. " + commProblem.Message + commProblem.StackTrace);
Console.Read();
wcfClient.Abort();
}
}
}
Article:
MSDN

Follow me on Twitter

Tuesday, June 9, 2009

Database checklist

Naming Guidline
-- Setup a standard for table/view/column/stored procedure names
-- Use full name , avoid abbrevations ( yes /no )
-- No underscores
-- Use pascal casing
-- Not more than three characters to name objects
-- If using any prefixes , standardize it
-- DataTypes standardization , GUID vs ID , Varchar minimum 100 length etc
-- Always use primary key
-- Use unique key constraint for other unique columns
-- Specify not null fields
-- Decide on maximum number of columns per table ( i.e. 20 )
-- Cascase delete ( yes / no )
-- No inline t-sql command, use only stored procedures
-- Do not use SELECT * in queries
-- For large table index the columns most commonly used
-- Store sensitive data ( passwords, credit card , ssn etc ) in encrypted format
-- Use Triggers wisely
-- T-SQL command should order the results in case its master data used in Selection Controls like drop down.

Security
-- Use Database roles / Application roles ( read/read-write )
-- Permission should be granted on tables / view , only for stored procedures

Quality
-- Header comment to discribe the purpose of stored procedure and application details
-- Inline comment with in stored procedures

Clean-up
-- Plan for clean-up scripts to move/ delete old data
-- Back up schedules

Articles:
Guidelines

Follow me on Twitter

Thursday, June 4, 2009

Retract/Deloy solution or Upgrade solution ?

Scenario:
I got this question all the time about best way to upgrade the solution already deployed to the farm.

Solution:
There is no simple answer to the question.As it totally depends upon artifacts and also STSADM commands have limitations.

STSADM UpgradeSolution:
Upgrading a solution involves replacing a previous version of a solution with a current version of the solution. Specifically, an upgrade occurs when a solution is deployed that shares a solution ID with another solution.

During upgrade, files that are associated with the previous version of a solution are removed, and files contained in the current version are added.You can add new files in a solution upgrade and remove old versions of the files, but you cannot install Features or use Feature event handlers to run code for Feature installation and activation.

STSADM Retract Deploy Solution:
Retracting a SharePoint solution does not remove any information from the content database. Therefore, sites are intact after redeployment.

Similarly, you must include SharePoint feature deactivation in the installation script if you want deactivation logic to execute before retracting the original SharePoint solution. You should use caution with this approach if you do not have a time when the sites that use the solution can be taken offline. If a site is based on a site definition that is being removed and reinstalled, users will experience unpredictable behavior during the upgrade process.

Common Behaviour:
You must reactivate any installed features on any sites that use the SharePoint features

Article:
MSDN , MSDN , P&P Good Example

Follow on Twitter

Saturday, May 30, 2009

Validating Content type name

Scenario:
Validating content type name while creating programaticaly

Solution:
Code:

// Decide on a name for the new content type.
string contentTypeName = "R&D";
try
{
SPContentType.ValidateName(contentTypeName);

}
catch (SPException ex)
{
Console.WriteLine(ex.Message);
}
Output
The content type name cannot contain: \  / : * ? " # % < > { } | ~ &, two consecutive periods (..), or special characters such as a tab.

Sunday, October 12, 2008

Caching in WebParts

Scenario:
You want to use caching in webpart

Solution:
Webpart is just like any other WebControl and can use caching object.

Code:

using System; 
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using Microsoft.SharePoint;
using System.Web;

namespace TrainingSamples {

public class SimpleCache: System.Web.UI.WebControls.WebParts.WebPart {

protected override void Render (System.Web.UI.HtmlTextWriter writer) {

base.Render (writer);

List<SPList> lists = new List<SPList>();
string status = "";

if (HttpRuntime.Cache["SimpleSampleCache"] == null)
{
status = "The following items are NOT <strong> </ strong> fetched from the cache <br/>";

SPWeb web = SPContext.Current.Web;
foreach(SPList list in web.Lists)
{
lists.Add (list);
}

HttpRuntime.Cache.Add( "SimpleSampleCache" lists, null DateTime.MaxValue, TimeSpan.FromMinutes(10), System.Web.Caching.CacheItemPriority.Default, null);
}
else
{
status = "The following items ARE <strong> </ strong> fetched from the cache! <br/>";
list = (List<SPList>) HttpRuntime.Cache["SimpleSampleCache"];
}

writer.Write (status);

foreach (l in SPList lists)
{
writer.WriteLine (l.Title + "-" + + l.ItemCount "items <br/>");
}
}
)
)
Note:
Another best practice is consider loading the data from SharePoint objects into a DataSet or DataTable if caching is required.
Article:
http://blogs.msdn.com/modonovan/archive/2005/04/27/412505.aspx

Deliver SharePoint ( Some Tips )

Article:

Eleven ways to make your SharePoint implementation more user-friendly
http://amatterofdegree.typepad.com/a_matter_of_degree/2008/06/eleven-ways-to.html

Best Practices: Using Disposable Windows SharePoint Services Objects
http://msdn.microsoft.com/en-us/library/aa973248.aspx

http://blogs.msdn.com/rogerla/archive/2008/02/12/sharepoint-2007-and-wss-3-0-dispose-patterns-by-example.aspx

http://blogs.msdn.com/sowmyancs/archive/2008/10/26/best-practices-sharepoint-object-model-for-performance-tuning.aspx