Wednesday, December 17, 2008

Simple STSADM Commands

I thought these are some of the commands we use (may not be in day to day operations) that can be handy.

InstallFeature:
stsadm -o installfeature -filename "MyFeature\Feature.xml"
use -force to force override

Sunday, November 16, 2008

Programatically Reading a list and binding to SPGridView (Code)

This post would depict the simple usage of SPGridView and reading from a list and binding it to the SPGridView programatically.


SPGridView oSPGridView = new SPGridView();
string sTaskListName = "News"; // News List in this example

SPWeb site = SPControl.GetContextWeb(Context);
SPList spList = site.Lists[sTaskListName];

SPDataSource mySPDS = new SPDataSource();
mySPDS.List = spList;

oSPGridView.DataSource = mySPDS;
oSPGridView.DataBind();

Get SharePoint Site Collection (Code)

private static Dictionary GetSites()
{
Dictionary sites = new Dictionary(32);



WSSModule.WebAppOp(
delegate(SPWebApplication webapp)
{
foreach (SPSite site in webapp.Sites)
{
try
{

using (SPWeb web = site.RootWeb)
{
if (web.DoesUserHavePermissions(SPBasePermissions.ViewPages))
sites.Add(web.ServerRelativeUrl, web.Title);
}

} catch(SPException)
{

}
}
}
);


return sites;

}

SharePoint Site (individual) Provisioning (Code)

in my previous blog for SharePoint Site Provisioning (Code), it is only used when you are creating sites for the first time. Now imagine if you have already and site and you want to add another site to the WebApp individually. You might want to consider the below.


public static string CreateClientSite(SPWebApplication app, string path, int siteId, string title, string owner)
{
string url;

if (string.IsNullOrEmpty(owner) owner == "{current}")
{
IIdentity identity = System.Threading.Thread.CurrentPrincipal.Identity;
WindowsIdentity winIdentity = identity as WindowsIdentity;
owner = winIdentity != null ? winIdentity.Name : clientSiteOwner;
}

using (SPSite site = app.Sites.Add(string.Format(path, siteId),
title, string.Empty, 1033, null, owner,
"Application Admins",
"<EmailID>"))
{
url = SetWebSettings(site, siteId);
}

return url;
}

private static string SetWebSettings(SPSite site, int siteId)
{
string url;
using (SPWeb web = site.RootWeb)
{
web.Properties<:Property>] = <VALUE>;
web.Properties.Update();
web.ApplyWebTemplate(<TemplateId>);

url = web.ServerRelativeUrl;
}
return url;
}

SharePoint Site Provisioning (Code)

// FIRT TIME COMPLETE SITE PROVISIONING. YOU MIGHT NOT RUN THIS EVERY TIME
try
{
// JOB STARTING

SPWebApplication app = SPWebApplication.Lookup(new Uri(ConfigurationCollection.Instance.ApplicationPath));

List allowPrefixes = new List();
foreach (Configuration usersGroup in ConfigurationCollection.Instance.Configurations)
{
allowPrefixes.Add(usersGroup.SitesLocation);
}

List siteNames = new List();
WebApp.ProcessSites(true, app, delegate(SPSite site)
{
using (SPWeb root = site.RootWeb)
{
foreach (string prefix in allowPrefixes)
{
if (root.ServerRelativeUrl.TrimStart('/').StartsWith(prefix))
{
siteNames.Add(root.ServerRelativeUrl.TrimStart('/'));
root.Properties[WebApp.propPKIDiSDirty] = "true";
root.Properties.Update();
return;
}
}
}
});



foreach (Configuration configuration in ConfigurationCollection.Instance.Configurations)
{
Configuration configuration1 = configuration;
ProvisioningModule.ProcessConfig(configuration,
delegate(Dictionary userInfo)
{
string url = ProvisioningModule.GetEntityRelativeUrl(userInfo);
if (!siteNames.Contains(url))
{
using (SPSite site =
CreateSite(app, url, Formatter.GetFormatString(Convert.ToString(userInfo[ProvisioningModule.fieldEntityFormatField]), userInfo),
configuration1, userInfo))
using (SPWeb root = site.RootWeb)
{
root.Properties[WebApp.propPKID] =
userInfo[ProvisioningModule.fieldPKID].ToString
();
root.Properties.Update();
}
Log.Trace(Level.Info, "Created site{0}", url);
Console.WriteLine("Created site {0}", url);
}
else
{
SPSecurity.RunWithElevatedPrivileges(delegate {
using (SPSite site = new SPSite(WebApp.ApplicationPath + url))
using (SPWeb web = site.RootWeb)
{
web.Properties[WebApp.propPKIDiSDirty] = "false";
web.Properties.Update();
}
});
// UPDATED SITE

}
});
}

if (ConfigurationCollection.Instance.PerformArchival)
{
WebApp.ProcessSites(true, app,
delegate(SPSite site)
{
using (SPWeb root = site.RootWeb)
{
if (null != root.Properties[WebApp.propPKIDiSDirty] && root.Properties[WebApp.propPKIDiSDirty].Contains("true"))
{
if (!string.IsNullOrEmpty(ConfigurationCollection.Instance.ArchiveLocation))
ReloacateSite(app.Sites, site,
ConfigurationCollection.Instance.ApplicationPath + ConfigurationCollection.Instance.ArchiveLocation +
site.ServerRelativeUrl);
else
StripAccess(root);
}
}
}
);
}
// JOB FINISHING
}
catch (Exception e)
{
// JOB ABORTED
}

Creating SP Site Feature

This post would make one understand in simple 10 steps how to create and deploy a SharePoint Site Feature (in this case a page).

This is simple but very useful in case of you already have an existing portal and want to deploy a new page / item (could be anything) when there is no provision to modify ONET.xml file.

Step 1 # Create a folder in the web project (you can create any where... using Visual Studio is not a mandate here) with the name of the Site Feature you want to deploy to the SP Site / Web. NewFeaturePage in this example. It is preferable to have no space in the Feature name but thats not mandatory. Best practices suggests to have 'u20' (html encoded) to replace spaces in the feature name.
Step 2 # Add a (new) XML File to the folder and name it as Elements.xml
Step 3 # Create a new .aspx page to the folder and name it as NewFeaturePage.aspx (in this example)
Step 4 # Add a (new) XML File to the folder and name it as Feature.xml
Step 5 # From VS Designer, TOOLS > CREATE GUID create a new GUID. Use this new GUID in the Feature.xml as shown below for Feature ID.

the contents of Elements.xml can be as simple as below...
------------------------------------------------------------------------
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Module Name="NewFeaturePage" Path="" Url="" >
<File Url="NewFeaturePage.aspx" Type="Ghostable" IgnoreIfAlreadyExists="FALSE" />
</Module>
</Elements>
------------------------------------------------------------------------
the contents of Feature.xml would be as below...
------------------------------------------------------------------------
<Feature
Id="{USE THE NEW GUID HERE}"
Title="New Feature"
Description="New Feature"
Scope="Web"
xmlns="http://schemas.microsoft.com/sharepoint/"
Hidden="False"
>
<ElementManifests>
<ElementManifest Location="Elements.xml" />
</ElementManifests>
</Feature>
------------------------------------------------------------------------

Step # 6 Copy the NewFeature folder from your project or local folder) to the following location on the SharePoint Server box. If you followed Step 1 - 6 by log in to the SP Server box, copy the folder locally.

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\

SKIP THE BELOW STEP IF YOU ARE ON SP SERVER BOX ALREADY
Step # 7 Logon to SP Server box.

Step # 8 If you have map path to stsadm run the below command directly. Else, map to the C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\bin\

stsadm -o installfeature –filename NewFeature\Feature.xml

This would install the feature

Step # 9 C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\bin\

stsadm -o activatefeature –filename NewFeature\Feature.xml -url http://ServerName/Sitecollection

This would activate the feature.

and now one should be able to access the NewFeaturePage.aspx page from http://ServerName/NewFeaturePage.aspx (based on where you deploy as part of your Elements file File URL Property).

Saturday, November 15, 2008

SharePoint - Add Users (Code)

private void Button1_Click(object sender, System.EventArgs e)
{
SPWeb web = SPControl.GetContextWeb(Context);
string username = TextBox1.Text;
string displayname = TextBox2.Text;
string email = TextBox3.Text;

SPRole admins = web.Roles["Administrator"];
try
{
admins.AddUser(username,email,displayname,"");
Label4.Text="Successfully added user";
}
catch(Exception ex)
{
Label4.Text=ex.ToString();
}
}

SharePoint - Copy Files (Code)

private SPWeb web;

private void Page_Load(object sender, System.EventArgs e)
{
web = SPControl.GetContextWeb(Context);
}


private void Button1_Click(object sender, System.EventArgs e)
{
int maxsize = Convert.ToInt32(TextBox1.Text);
SPFolder myfolder=web.GetFolder("Shared Documents");
SPFileCollection myfiles = myfolder.Files;
foreach (SPFile file in myfiles)
{
if (file.Length>(maxsize*1024))
{
Response.Write(file.Name + ": " + file.Length/1024 + "kb
");
file.CopyTo("Archive/"+file.Name,true);
}
}
}

CAML Query Builder

http://www.u2u.info/Blogs/karine/Lists/Posts/Post.aspx?ID=28

from Karine Bosch.

Friday, November 14, 2008

Collabarative Application Markup Language (CAML)

CAML (Collaborative Application Markup Language) is an XML based markup language used with the family of Microsoft SharePoint technologies (Windows Sharepoint Services and Office SharePoint Server). Unlike plain XML, CAML contains specific groups of tags to both define and display (render) data.

CAML allows developers to both construct and display data. Microsoft refers to elements used to display data as "Rendering" elements.

In general, most of all xml files in a sharepoint installation include CAML. Specifically CAML is very important in site and list definitions, via the Onet.xml files as well as other corresponding xml files. Here the CAML is used to define what elements exist on an instance of a site, and the display of these sub-elements, while the aspx files are used to define how to arrange and display those elements to form the site.
CAML is also used to query against Sharepoint lists and views, when programming against the SharePoint API.

CAML can be used to do the following:

1. Provide schema definition to the Web site provisioning system about how the site looks and acts.
2. Define views and forms for data and page rendering or execution.
3. Act as a rendering language that performs functions in the DLL like pulling a value from a particular field.
4. Provide batch functionality for posting multiple commands to the server using protocol.

Why would you use CAML as opposed to just using Microsoft FrontPage® or other editing tools?

1. To make universal changes, such as adding a new logo to the main pages of every site you create.
2. To define a content type, such as for adding Flash movies to the SharePoint team Web site.
3. It provides the ultimate in customization and flexibility; manipulating CAML allows you total control over the site provisioning system, for instance, when creating a list or adding a view.

CAML Queries:

CAML can be used to query data from various lists. See the below example...

SPWeb web = SPControl.GetContextWeb(this.Context);
SPView view = web.Lists["List Name"].Views["Search"];

// create a List View called "Search"

// Get
string query = view.Query;

// Set
view.Query = query;
view.Update();

String query = "";

// Some of other query conditions
query += ""; // Condtion
query += ""; // Operator
query += ""; // Field Name
query += "a"; // Value
query += "
"; // Close tags

-------------------------------------------------------------------
Resources : Google Search

SP Site Architecture

SP Object Model

Monday, July 14, 2008

Creating a simple HttpHandlers

This is a simple post to demonstrate how to create a simple httphandler to download a pdf (or any excel / doc etc).

This might coincide with many other blogs in contents because I had this learning from many other websites (BoilerPlate is one among).

Lets start...

Step 1:
Create a project (C#/VB) and add a class (some thing like HttpHandlerBase.cs) that inherits from IHttpHandler

Step 2:
Make sure you implement the method ProcessRequest

Step 3:
Make sure you implement the property IsReusable

Step 4:
This class can be made abstract on need basis

Step 5:
If not step 4, implement your code for downloading the PDF. Else, from another class inherit the above class and override the processrequest method and write your implementation.

Step 6:
Inside Web.Config, under httpHandlers section add verb
<add verb="GET" path="DownloadPdf.ashx" type="Assembly Information, NameSpace" validate="false" />

Step 7:
from any page you want to call, just call the link as below:
<asp:HyperLink ID="link1" runat="server" NavigateUrl="DownloadPdf.ashx"/>

Note the DownloadPdf.ashx, i am following the same path name. Incase you want any .ashx, replace the verb path to path="*.ashx" to divert all the calls to the above mentioned assembly.
//____________________________________________________________
//Code
//------------------------------------------------------------
// HTTPHANDLER BASE CLASS
//------------------------------------------------------------
using System;
using System.Net;
using System.Web;

// This Abstract class is taken from
// http://haacked.com/archive/2005/03/17/AnAbstractBoilerplateHttpHandler.aspx
namespace CodeName.Srini.HttpHandlers
{
/// 
/// An abstract base Http Handler for all your
/// needs.
/// 
/// 
/// 
/// For the most part, classes that inherit from this
/// class do not need to override .
/// Instead implement the abstract methods and
/// properties and put the main business logic
/// in the .
/// 
/// 
/// HandleRequest should respond with a StatusCode of
/// 200 if everything goes well, otherwise use one of
/// the various "Respond" methods to generate an appropriate
/// response code. Or use the HttpStatusCode enumeration
/// if none of these apply.
/// 
/// 
public abstract class HttpHandlerBase : IHttpHandler
{
public HttpHandlerBase()
{
// Default Constructor
}

/// 
/// Processs the incoming HTTP request.
/// 
/// 
Context.public void ProcessRequest(HttpContext context)
{
SetResponseCachePolicy(context.Response.Cache);

if (!ValidateParameters(context))
{
RespondInternalError(context);
return;
}

if (RequiresAuthentication
&& !context.User.Identity.IsAuthenticated)
{
RespondForbidden(context);
return;
}

context.Response.ContentType = ContentMimeType;

HandleRequest(context);
}

/// 
/// Indicates whether or not this handler can be
/// reused between successive requests.
/// 
/// 
/// Return true if this handler does not maintain
/// any state (generally a good practice). Otherwise
/// returns false.
/// 
public bool IsReusable
{
get
{
return true;
}
}

/// 
/// Sets the cache policy. Unless a handler overrides
/// this method, handlers will not allow a respons to be
/// cached.
/// 
/// 
Cache.public virtual void SetResponseCachePolicy(HttpCachePolicy cache)
{
cache.SetCacheability(HttpCacheability.NoCache);
cache.SetNoStore();
cache.SetExpires(DateTime.MinValue);
}

/// 
/// Validates the parameters. Inheriting classes must
/// implement this and return true if the parameters are
/// valid, otherwise false.
/// 
/// 
Context./// true if the parameters are valid,
/// otherwise false
public abstract bool ValidateParameters(HttpContext context);

/// 
/// Helper method used to Respond to the request
/// that an error occurred in processing the request.
/// 
/// 
Context.protected void RespondInternalError(HttpContext context)
{
// It's really too bad that StatusCode property
// is not of type HttpStatusCode.
context.Response.StatusCode =
(int)HttpStatusCode.InternalServerError;
context.Response.End();
}

/// 
/// Gets a value indicating whether this handler
/// requires users to be authenticated.
/// 
/// 
/// true if authentication is required
/// otherwise, false.
/// 
public abstract bool RequiresAuthentication { get; }

/// 
/// Helper method used to Respond to the request
/// that the request in attempting to access a resource
/// that the user does not have access to.
/// 
/// 
Context.protected void RespondForbidden(HttpContext context)
{
context.Response.StatusCode
= (int)HttpStatusCode.Forbidden;
context.Response.End();
}

/// 
/// Gets the content MIME type.
/// 
/// 
public abstract string ContentMimeType { get; }

/// 
/// Handles the request. This is where you put your
/// business logic.
/// 
/// 
/// 
This method should result in a call to one
/// (or more) of the following methods:
/// 
context.Response.BinaryWrite();
/// 
context.Response.Write();
/// 
context.Response.WriteFile();
/// 
/// 
/// someStream.Save(context.Response.OutputStream);
/// 
/// 
/// 
etc...
/// 
/// If you want a download box to show up with a
/// pre-populated filename, add this call here
/// (supplying a real filename).
/// 
/// 
/// 
/// Response.AddHeader("Content-Disposition"
/// , "attachment; filename=\"" + Filename + "\"");
/// 
/// 
/// 
Context.public abstract void HandleRequest(HttpContext context);
}
}

//------------------------------------------------------------
// DERIVED CLASS
//------------------------------------------------------------

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;

namespace CodeName.Srini.HttpHandlers
{
public class DownloadPublishedReport : HttpHandlerBase
{
private const string NoDataMessage = "No downloadable pdf file available for this record.";

public override bool ValidateParameters(HttpContext context)
{
return true;
}

public override bool RequiresAuthentication
{
get { return false; }
}

public override void HandleRequest(HttpContext context)
{
DownloadFileFromServer(context);
}

public override string ContentMimeType
{
get { return "application/pdf"; }
}

private void DownloadFileFromServer(HttpContext context)
{
string pdfFileName = string.Empty;
Byte[] pdfData = null;

// CREATE UR OWN DATAVIEW TO GET THE BYTE CODE AND THE FILE NAME FOR PDF
if (dv != null)
{
if (dv.Table.Rows.Count > 0)
{
DataRow dr = dv.Table.Rows[0];

pdfFileName = dr[1].ToString();
pdfData = (byte[])(dr[4]);
}
}

if (pdfData != null)
{
BuildPdfAndDownload(context, pdfData, pdfFileName);
}
else
{
byte[] buffer = new byte[NoDataMessage.Length];

System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
buffer = encoding.GetBytes(NoDataMessage);

BuildPdfAndDownload(context, buffer, "NoData.pdf");
}
}

private void BuildPdfAndDownload(HttpContext context, Byte[] pdfData, string pdfFileName)
{
context.Response.Buffer = true;
context.Response.Clear();
context.Response.ContentType = "application/octet-stream";

context.Response.AddHeader("content-disposition", "attachment;filename=" + pdfFileName);
context.Response.AddHeader("content-length", pdfData.Length.ToString());
context.Response.BinaryWrite(pdfData);

context.Response.End();
}
}
}

//------------------------------------------------------------
// WEB.CONFIG SETTINGS
//------------------------------------------------------------

<httpHandlers>
<add verb="GET" path="DownloadPdf.ashx" type="CodeName.Srini.HttpHandlers.DownloadPublishedReport, CodeName.Srini.HttpHandlers" validate="false" />
</httpHandlers>

//------------------------------------------------------------
// CALLING ASPX PAGE
//------------------------------------------------------------

<asp:HyperLink ID="link1" runat="server" NavigateUrl="DownloadPdf.ashx" />

Saturday, June 28, 2008

Inside Arrays

[Reference : Bill McCarthy - http://msmvps.com/bill ] - I Liked this and I had the direct content on my Blog. Thank you Bill for a nice Editorial.

Inside Arrays

Drill down on how arrays work and learn some cool tips and tricks for taking advantage of them in .NET.

July 2008 · by Bill McCarthy

TECHNOLOGY TOOLBOX: VB.NET

Arrays are fundamental building blocks for in-memory storage. Arrays are pervasive in .NET, forming the major backbone of many classes, including virtually all collections. Yet many myths surround arrays, their type safety, and their ability to have non-zero bounds. Where there are myths, there are often coding practices that fail to recognize true best practices.

Expect to see Windows 7 arriving sometime around January of 2010, Veghte wrote.

Addressing the Microsoft partner community, Veghte confirmed that Windows 7 will not be a new kernel, but will be built on Windows Vista. Partners can expect less of a surprise in terms of integration and migration efforts than was the case with Vista.

"You've also let us know you don't want to face the kinds of incompatibility challenges with the next version of Windows you might have experienced early with Windows Vista," Veghte explained. "As a result, our approach with Windows 7 is to build off the same core architecture as Windows Vista so the investments you and our partners have made in Windows Vista will continue to pay off with Windows 7. Our goal is to ensure the migration process from Windows Vista to Windows 7 is straightforward."

So does June 30 really signal the end of Windows XP? The answer is that Windows XP is not quite dead yet, but it is mortally wounded, and will limp along under the legal fine print for a few more years.

For instance, Microsoft plans to continue to provide security updates for Windows XP Service Pack 3 until April of 2014, Veghte explained. So current users of Windows XP can expect almost six more years of patch support.

In terms of buying Windows XP directly instead of Windows Vista, that's a little tricky. Microsoft plans to license Windows Vista Home Edition and Windows XP Starter to low-cost computer makers. XP won't be available for new state-of-the-art PCs after June 30, but there's potentially an extension to that deadline if the PC comes from a "system builder." A Microsoft spokesperson dedescribed the availability of XP licensing by e-mail in this way:

"Windows XP will no longer be available for purchase from Microsoft for general retail and OEM partners as of June 30, 2008
System builders will be able to purchase until January 31, 2009
For Windows XP Starter (in emerging markets) and Windows XP Home for NetBooks and NetTops (formerly known as ULCPCs), the date is June 30, 2010
Per our longstanding practice allowing 'downgrade' rights, enterprise customers and purchasers of Windows Vista Ultimate or Windows Vista Business editions can choose to downgrade to Windows XP Professional if they feel they need more time to get ready for Windows Vista."
The difference between a system builder and an original equipment manufacturer (OEM) such as Dell or HP is that an OEM buys software licensing directly from Microsoft, whereas system builders buy it from distributors, the spokesperson explained. The extended date for system builders isn't a loophole but is part of Microsoft's licening agreement, she added.

"As of Jan. 31, 2009 system builders will no longer be able to get XP from Microsoft," the spokesperson wrote. "Whatever stock they still have at this point, they can use as they wish."

An example of a "NetTop" OEM is Asus with its compact Eee PC offering using XP Home. The One Laptop per Child association falls into the emerging market supplier camp. OLPC had been using open-Sugar Linux OS to supply computers to underprivileged kids, but it also plans to use Windows XP.

OEM computer equipment maker Dell pushed out its June 18 deadline of offering new PCs with Windows XP to June 26. The offer applies to Dell's "XPS 630, 720 H2C and M1730 systems." After that time, users can buy Windows Vista Business or Windows Vista Professional and downgrade to XP Professional. However, it'll cost up to $50 to do so.

Only those who buy Vista Business or Vista Ultimate editions will have XP downgrade rights, and they can only downgrade to XP Professional. Windows Vista Enterprise licensees have similar downgrade rights. Those purchasing the less expensive Vista Basic or Vista Home Edition will not have such XP downgrade rights.

It may still be possible for those wanting to get Windows XP after the June 30 date to find the boxed software from a retail outlet or over online sales such as E-Bay. The Microsoft spokesperson said that "Retailers and OEMs can keep selling XP for as long as they have stock."

About the Author

Kurt Mackie is online news editor, Enterprise Group, at 1105 Media Inc.

Thursday, June 19, 2008

Creating Editor Web Parts

When a page is placed in Edit Mode, a user can select to edit a Web Part's
control properties. An *EditorPart* control enables a user to edit an
associated Web Part control to modify its layout, appearance, properties,
behavior, or other related characteristics.

Sometimes the default functionality will not be enough for your needs. For
example, a Web Part could have a string property with complicated validation
logic behind it, or you may want a Web Part property to be a filter field.
You may also want a Web Part to be rendered like a drop-down list, which
will contain dynamically loaded information.

To create an *EditorPart* control, you need to implement a control that
derives from the *EditorPart* class. Next, you will have to override the *
ApplyChanges* and the *SyncChanges *methods. *ApplyChanges* applies changes
made in the editor control to the Web Part control being edited when the
user clicks OK or Apply. The *SyncChanges* method gets the current values of
the Web Part control being edited and passes them to the editor so that the
editor control can edit them (this also avoids synchronization problems
between the Web Part and the editor).

Next, to render your custom HTML, you need to override the *
CreateChildControls* and the *RenderContents* functions.

Here is an example of a skeleton for a ZIP Code editor part, which provides
a text box where you can enter a ZIP Code as well as validate it.

public class ZipCodeEditor : EditorPart
{
TextBox input = null;
Label displaymessage = null;
Literal lineBreak;
protected override void CreateChildControls()
{
Controls.Clear();
input = new TextBox();
this.Controls.Add(input);
lineBreak = new Literal();
lineBreak.Text = @"
";
Controls.Add(lineBreak);
displaymessage = new Label();
this.Controls.Add(displaymessage);
}
protected override void RenderContents(HtmlTextWriter writer)
{
writer.Write("
");
input.RenderControl(writer);
writer.Write("
");
displaymessage.RenderControl(writer);
}
public override bool ApplyChanges()
{
try
{
//validation logic

//if ValidationSuccessful
ZipCodeWebPart part = (ZipCodeWebPart)WebPartToEdit;
// Update the custom WebPart
part.ZipCode = input.Text;
}
catch (Exception exc)
{
//error handling
}
return true;
}
public override void SyncChanges()
{
input.Text = ((ZipCodeWebPart)WebPartToEdit).ZipCode;
}
}

To associate the editor part with your Web Part, you will need to override
the *CreateEditorParts* method in the Web Part where you will create the
instances of the editor parts. An example of this is as follows:

public class ZipCodeWebPart : System.Web.UI.WebControls.WebParts.WebPart
{
protected string _zipcode;
public ZipCodeWebPart()
{
//
}
[Personalizable(PersonalizationScope.Shared), WebBrowsable(false),
WebDisplayName("ZipCode"),
WebDescription("The ZipCode")]
public string ZipCode
{
get { return _zipcode; }
set { _zipcode = value; }
}
public override EditorPartCollection CreateEditorParts()
{
ArrayList editorArray = new ArrayList();
ZipCodeEditor edPart = new ZipCodeEditor();
edPart.ID = this.ID + "_editorPart1";
editorArray.Add(edPart);
EditorPartCollection editorParts =
new EditorPartCollection(editorArray);
return editorParts;
}
protected override void RenderContents(HtmlTextWriter writer)
{
//
}
protected override void Render(HtmlTextWriter writer)
{
//
}
}

How to Export Sharepoint Site and Data?

Use the following command to export complete site information. It shall copy data, list schema, pages, onet and every other thing. However if you configure the view on the webpart zone, it doesnt pick the view.

stsadm -0 export -url http:/// -filename .bak -includeusersecurity -versions 4

Thursday, June 12, 2008

Creating WebBrowsable Properties in WebParts

use WebBrowable along with Personalizable attribute on the Public Property to get property visible in the Editors Section.

for example if you want to display the Public Property Show Zipcode... use the below code.

private string _sZipCode;
[WebBrowsable]
[Personalizable]
Public string SetZipCode
{
get {return _sZipCode; }
set {_sZipCode = value; }
}

this would appear in the Misc Section when Modify Webpart is selected.

Monday, June 9, 2008

Sharepoint Layout Toggle Command

if you want to togle the page (sharepoint) to design mode; then use this command directly on the browser: javascript:MSOLayout_ToggleLayoutMode();