Wednesday, November 21, 2007

Extending STSADM OPERATION

I am trying to explore the functionality of stsadm operation, i have seen lot of blogs extending the stsadm operation.
for example, stsadm -o back http://myportal" c:\bacl.bak , this operation used to take a backup.
if i need to display/delete all the Sites,subsites(sites under subsites), there is no direct command to get this functionality.
We can achive this functionality extending the stsadm operation.So i am going to write the operation as DisplaySites/DeleteSites, which means it will delete the sites/webs/sites under web.(Recursive).
My Stsadm tool will look like this
stsadm -o displaysites -url "http://myportal

There are two steps required to achieve this functonality
1.create a class which implements ISPStsadmCommand
2.Create a xml which has the public key token of class file and placed in (config folder : c:\program files\common file\microsoft shared\webserver extension\12 \config\
xmlfilename should be like this
stsadmcommands.customsitedelete.xml

Now will get into example

namespace CustomStsCommand.DisplaySites
{
public class DisplaySite : ISPStsadmCommand
{
#region ISPStsadmCommand Members

public string GetHelpMessage(string command)
{
return "-url \r\n" + "Display the web and Subsites";
}

public int Run(string command, System.Collections.Specialized.StringDictionary keyValues, out string output)
{
SPSite site = null;
SPWeb web = null;
output = string.Empty;

if (keyValues.Count == 2)
{
if (keyValues["url"] == null)
{
output += "Not valid command parameter";
return 1;
}


try
{
site = new SPSite(keyValues["url"]);
web=site.OpenWeb();

if (web == null)
output = "Web not found";
else
{
if (site.Url == web.Url)// Check because Openweb returning top level site if url passed doesn't exist
{
return 1;
}
DisplayWebRecursive(web.Webs,output);
if (web.Url==keyValues["url"])
{
output = output + web.Title.ToString();
}
return 1;
}
}
catch (Exception ex)
{
output = ex.Message;
}
finally
{
if (site != null) site.Dispose();
if (web != null) web.Dispose();
}
}
else
{
output = "Invalid number of parameters or missing parameters";
}
return 1;
}

public string DisplayWebRecursive(SPWebCollection webs,string output)
{
foreach (SPWeb wb in webs)
{
if (wb.Webs.Count > 0)
{
DisplayWebRecursive(wb.Webs,output);
}
output = output + wb.Title.ToString() + "\r\n"; //wb.Title.ToString();
}
return output;
}
#endregion
}
}

and Xml file looks like this





Hope this example helps you to achieve the stsadm extended functionality

Monday, November 19, 2007

Creating Hidden field in sharepoint.

In sharepoint developement, we might require to create column which should not display while adding an item/or editing an item.
for example, Current status is the column which is not required to show this column when end user while editing or adding an item.we can achieve this by using the below code.
you can create this type of field by using below sample code.

SPSite objSite = new SPSite("http://portal/");
SPWeb objWeb = objSite.OpenWeb();
SPFieldCollection fields = objWeb.Lists["Oppurtunites"].Fields;
string newField = "";
fields.AddFieldAsXml(newField, true, SPAddFieldOptions.Default);
Current Status is field created which doesnt appear while adding an item/editing an item thru sharepoint UI.

Adding Server Side code Blocks in custom pages using sharepoint designer

In some situation we might require to add server side code in sharepoint.Generally we can do this by adding the server side code aspx in layout folder.For example, I need to run one custom aspx with server side code, then i need to place this file under layouts folder.so that i can call this page in sharepoint.But this page is under file system and not in the sharepoint content DB.

Here we are trying to explore how to add a custom code in custom page using sharepoint desinger.

To demonstra this, add a new .aspx page from sharepoint designer.

add the below code...






Add this configuration to web.config file


Wednesday, November 7, 2007

Use of Import and Export utiltiy in sharepoint 2007

I am speding time of taking backup and restore, i have come across an option of using import and export.
import and export used to create a site bacup and can restore at different site collection.the only disadvantage of using this, not to able to restore the pages modified by sharepoint designer.

Syntax for using this tool.

stsadm.exe -o export -url http://samplesite/sites/mysite -filename "c:\mysite"

stsadm.exe -o import -url http://production.sites/mysite -filename "c\mysite.cmp".

Tuesday, November 6, 2007

Backup and Restore

I recently spent time on Backup and Restore on sharepoint 2007.I tried different option to take backup and resotre the sharepoint site.Each and every method has its own advantages and disadvantages.

There are three ways to take backup and restore.
1.Using web interface of sharepoint administration
2.using stsadm.exe
3.Take the sql content database backup and restore the same the content db and add this db at the site collection.
WebInterface.
This is one of the easiest method to take backup and restore too.
Steps to take Backup using Sharepoint central administration tool.
1.Go to sharepoint central administraion from start - Programs - > Sharepoint Central Administraion.
2.One the page is opened , Click on operation from left side navigation menu.
3.Click the "Perform Backup " from the menu Backup and Restore.
4.once you click, sharepoint takes you to another webpage, it shows all the webapplication to take the backup.
5.Select the webapplication to takeup backup.
6.Click the link "Continue to backup options"
7.System takes you to another screen , where we need to give the name of the backup file and where to store this backup file.
8.Click ok to take backup.
This creates a timer job in sharepoint.you can see this job under sharepoint timer jobs definition under "Global Configuration".
2.Backup using stsadm.
stsadm.exe is under "\program files\common files\microsoft shared\web server extenstion\12\bin.
the Syntax to take the backup
stsadm.exe -o backup -url "the webapplication url/site collection url" -filename "filename.bak"
to get the help for backup options
stsadm.exe -help backup

Third method is easy, take the content database backup as how we do take the backup from sql server.this is sql server backup procedure.

Code Analysis tool in VS 2005

I have been asked to do the code review for one of the projects. I am looking for the tool within VS.2005.I remembered when i install the VS.2005, I have seen some menu called "Code Analsyis , Performance and Testing.I Planned to try out the tool .

Based on the guidelines by microsoft site, i have described below , how to use this tool easily and quickly to review the code.

Steps to Use the Code Analysis Tool using VS.2005

1.Install the Code Analysis tool from the VS.Net 2005 setup.
2.Once you the tool, you will be able to see the code Analysis menu in Project Properties as below.












3.In this section, Developer can set the rules inorder to maintaint the standards.Microsoft uses an FxCop tool internally for thier developement.They defined the set of common rules used at their developement center.I have listed down the set of rules here.
Design
CA1008 EnumsShouldHaveZeroValue
CA1009 DeclareEventHandlersCorrectly
CA1011 ConsiderPassingBaseTypesAsParameters
CA1012 AbstractTypesShouldNotHaveConstructors
CA1014 MarkAssembliesWithClsCompliant
CA1017 MarkAssembliesWithComVisible
CA1018 MarkAttributesWithAttributeUsage
CA1019 DefineAccessorsForAttributeArguments
CA1023 IndexersShouldNotBeMultidimensional
CA1025 ReplaceRepetitiveArgumentsWithParamsArray
CA1026 DefaultParametersShouldNotBeUsed
CA1027 MarkEnumsWithFlags
CA1028 EnumStorageShouldBeInt32
CA1030 UseEventsWhereAppropriate
CA1032 ImplementStandardExceptionConstructors
CA1034 NestedTypesShouldNotBeVisible
CA1036 OverrideMethodsOnComparableTypes
CA1038 EnumeratorsShouldBeStronglyTyped
CA1039 ListsAreStronglyTyped
CA1040 AvoidEmptyInterfaces
CA1041 ProvideObsoleteAttributeMessage
CA1043 UseIntegralOrStringArgumentForIndexers
CA1044 PropertiesShouldNotBeWriteOnly
CA1045 DoNotPassTypesByReference
CA1046 DoNotOverloadOperatorEqualsOnReferenceTypes
CA1050 DeclareTypesInNamespaces
CA1051 DoNotDeclareVisibleInstanceFields
CA1052 StaticHolderTypesShouldBeSealed
CA1053 StaticHolderTypesShouldNotHaveConstructors
CA1054 UriParametersShouldNotBeStrings
CA1055 UriReturnValuesShouldNotBeStrings
CA1056 UriPropertiesShouldNotBeStrings
CA1057 StringUriOverloadsCallSystemUriOverloads
CA1058 TypesShouldNotExtendCertainBaseTypes
CA1059 MembersShouldNotExposeCertainConcreteTypes

Globalization
CA1300 SpecifyMessageBoxOptions
CA1301 AvoidDuplicateAccelerators
CA1304 SpecifyCultureInfo
CA1305 SpecifyIFormatProvider
CA1306 SetLocaleForDataTypes
CA1307 SpecifyStringComparison
CA1309 UseOrdinalStringComparison
CA2101 SpecifyMarshalingForPInvokeStringArguments

Interoperability
CA1401 PInvokesShouldNotBeVisible
CA1402 AvoidOverloadsInComVisibleInterfaces
CA1403 AutoLayoutTypesShouldNotBeComVisible
CA1404 CallGetLastErrorImmediatelyAfterPInvoke
CA1405 ComVisibleTypeBaseTypesShouldBeComVisible
CA1406 AvoidInt64ArgumentsForVB6Clients
CA1408 DoNotUseAutoDualClassInterfaceType
CA1413 AvoidNonpublicFieldsInComVisibleValueTypes

Naming
CA1700 DoNotNameEnumValuesReserved
CA1701 ResourceStringCompoundWordsShouldBeCasedCorrectly
CA1702 CompoundWordsShouldBeCasedCorrectly
CA1703 ResourceStringsShouldBeSpelledCorrectly
CA1704 IdentifiersShouldBeSpelledCorrectly
CA1707 IdentifiersShouldNotContainUnderscores
CA1708 IdentifiersShouldDifferByMoreThanCase
CA1709 IdentifiersShouldBeCasedCorrectly
CA1710 IdentifiersShouldHaveCorrectSuffix
CA1711 IdentifiersShouldNotHaveIncorrectSuffix
CA1712 DoNotPrefixEnumValuesWithTypeName
CA1713 EventsShouldNotHaveBeforeOrAfterPrefix
CA1714 FlagsEnumsShouldHavePluralNames
CA1715 IdentifiersShouldHaveCorrectPrefix
CA1716 IdentifiersShouldNotMatchKeywords
CA1719 ParameterNamesShouldNotMatchMemberNames
CA1720 IdentifiersShouldNotContainTypeNames
CA1721 PropertyNamesShouldNotMatchGetMethods
CA1722 IdentifiersShouldNotHaveIncorrectPrefix
CA1724 TypeNamesShouldNotMatchNamespaces

Performance
CA1811 AvoidUncalledPrivateCode
CA1812 AvoidUninstantiatedInternalClasses
CA1813 AvoidUnsealedAttributes
CA1815 OverrideEqualsAndOperatorEqualsOnValueTypes
CA1816 DisposeMethodsShouldCallSuppressFinalize
CA1819 PropertiesShouldNotReturnArrays

Portability
CA1900 ValueTypeFieldsShouldBePortable
CA1901 PInvokeDeclarationsShouldBePortable

Reliability
CA2001 AvoidCallingProblematicMethods
CA2002 DoNotLockOnObjectsWithWeakIdentity
CA2004 RemoveCallsToGCKeepAlive
CA2006 UseSafeHandleToEncapsulateNativeResources

Security
CA2102 CatchNonClsCompliantExceptionsInGeneralHandlers
CA2103 ReviewImperativeSecurity
CA2104 DoNotDeclareReadOnlyMutableReferenceTypes
CA2105 ArrayFieldsShouldNotBeReadOnly
CA2106 SecureAsserts
CA2107 ReviewDenyAndPermitOnlyUsage
CA2108 ReviewDeclarativeSecurityOnValueTypes
CA2109 ReviewVisibleEventHandlers
CA2111 PointersShouldNotBeVisible
CA2112 SecuredTypesShouldNotExposeFields
CA2114 MethodSecurityShouldBeASupersetOfType
CA2115 CallGCKeepAliveWhenUsingNativeResources
CA2116 AptcaMethodsShouldOnlyCallAptcaMethods
CA2117 AptcaTypesShouldOnlyExtendAptcaBaseTypes
CA2118 ReviewSuppressUnmanagedCodeSecurityUsage
CA2119 SealMethodsThatSatisfyPrivateInterfaces
CA2120 SecureSerializationConstructors
CA2121 StaticConstructorsShouldBePrivate
CA2122 DoNotIndirectlyExposeMethodsWithLinkDemands
CA2123 OverrideLinkDemandsShouldBeIdenticalToBase
CA2124 WrapVulnerableFinallyClausesInOuterTry
CA2126 TypeLinkDemandsRequireInheritanceDemands
CA2127 SecurityTransparentAssembliesShouldNotContainSecurityCriticalCode
CA2128 SecurityTransparentCodeShouldNotAssert
CA2129 SecurityTransparentCodeShouldNotReferenceNonpublicSecurityCriticalCode

Usage
CA1806 DoNotIgnoreMethodResults
CA2207 InitializeValueTypeStaticFieldsInline
CA2208 InstantiateArgumentExceptionsCorrectly
CA2209 AssembliesShouldDeclareMinimumSecurity
CA2211 NonConstantFieldsShouldNotBeVisible
CA2213 DisposableFieldsShouldBeDisposed
CA2214 DoNotCallOverridableMethodsInConstructors
CA2216 DisposableTypesShouldDeclareFinalizer
CA2217 DoNotMarkEnumsWithFlags
CA2218 OverrideGetHashCodeOnOverridingEquals
CA2220 FinalizersShouldCallBaseClassFinalizer
CA2221 FinalizersShouldBeProtected
CA2224 OverrideEqualsOnOverloadingOperatorEquals
CA2225 OperatorOverloadsHaveNamedAlternates
CA2227 CollectionPropertiesShouldBeReadOnly
CA2228 DoNotShipUnreleasedResourceFormats
CA2229 ImplementSerializationConstructors
CA2230 UseParamsForVariableArguments
CA2233 OperationsShouldNotOverflow
CA2234 PassSystemUriObjectsInsteadOfStrings
CA2235 MarkAllNonSerializableFields
CA2236 CallBaseClassMethodsOnISerializableTypes
CA2237 MarkISerializableTypesWithSerializable
CA2240 ImplementISerializableCorrectly

Non-Public Rule Set:

Globalization
CA2101 SpecifyMarshalingForPInvokeStringArguments

Portability
CA1900 ValueTypeFieldsShouldBePortable
CA1901 PInvokeDeclarationsShouldBePortable

Reliability
CA2002 DoNotLockOnObjectsWithWeakIdentity

Security
CA2100 ReviewSqlQueriesForSecurityVulnerabilities
CA2102 CatchNonClsCompliantExceptionsInGeneralHandlers
CA2103 ReviewImperativeSecurity
CA2104 DoNotDeclareReadOnlyMutableReferenceTypes
CA2105 ArrayFieldsShouldNotBeReadOnly
CA2106 SecureAsserts
CA2107 ReviewDenyAndPermitOnlyUsage
CA2108 ReviewDeclarativeSecurityOnValueTypes
CA2109 ReviewVisibleEventHandlers
CA2111 PointersShouldNotBeVisible
CA2112 SecuredTypesShouldNotExposeFields
CA2114 MethodSecurityShouldBeASupersetOfType
CA2115 CallGCKeepAliveWhenUsingNativeResources
CA2116 AptcaMethodsShouldOnlyCallAptcaMethods
CA2117 AptcaTypesShouldOnlyExtendAptcaBaseTypes
CA2118 ReviewSuppressUnmanagedCodeSecurityUsage
CA2119 SealMethodsThatSatisfyPrivateInterfaces
CA2120 SecureSerializationConstructors
CA2121 StaticConstructorsShouldBePrivate
CA2122 DoNotIndirectlyExposeMethodsWithLinkDemands
CA2123 OverrideLinkDemandsShouldBeIdenticalToBase
CA2124 WrapVulnerableFinallyClausesInOuterTry
CA2126 TypeLinkDemandsRequireInheritanceDemands
CA2127 SecurityTransparentAssembliesShouldNotContainSecurityCriticalCode
CA2128 SecurityTransparentCodeShouldNotAssert
CA2129 SecurityTransparentCodeShouldNotReferenceNonpublicSecurityCriticalCode

Usage
CA2233 OperationsShouldNotOverflow

4. Right click the project property.you can able to see the "Run Code Analysis".












5.Click the menu.
6.VS.NET creates set of warnings based on the rules defined and code.