Thursday, 15 November 2012

SharePoint 2010 search not returning any results despite of successful crawling

Hi Friends,

I would like to share a funny issue with SharePoint Server 2010 search.
I have configured Search Services application in SP2010 as per the instruction in MSDN Associated this services to the intended Web Application using Web Application associations. Performed a full crawl after adding the proper content sources. Happy to see a succesful crawl log. But when i tried to perform a search from the web application I am surprised to see no results in the OOTB search page.

After doing some further analysis, I could figure out the issue. While adding content sources, and within the local SharePoint Sites content source, I have added the Url of the web application with fully qualified domain name. However, I have Alternate Access mappings setup, where the default is pointing to the web application Url just with computer name and port number something like http:\\<computerName>:<portnumber>. Changed the default Alternate Access mapping to Fully Qualified Domain Name and could see the search results.

A simple trick. Hope this will help who is seeing a similar issue.

Cheers
Paramesh.

Tuesday, 27 May 2008

ASP.Net Page Life Cycle

Each request for an .aspx page that hits IIS is handed over to HTTP Pipeline. HTTP Pipeline is a chain of managed objects that sequentially process the request and convert it to plain HTML text content. The start point of HTTP Pipeline is the HttpRuntime class. The ASP.NET infrastructure creates each instance of this class per AppDomain hosted within the worker process. HttpRuntime class picks up an HttpApplication object from an internal pool and sets it to work on the request. It finds out what class has to handle the request. The association between the resources and handlers are stored in the configurable file of the application. In web.config and also in machine.config you will find these lines in section.

If you run through the following program, it will be much easier to follow

<add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory"/>

This extension can be associated with HandlerClass or HandlerFactory class. HttpApplication object gets the page object that implements the IHttpHandler Interface. The process of generating the output to the browser is started when the object calls ProcessRequest method.

Page Life Cycle

Once the HTTP page handler class is fully identified, the ASP.NET runtime calls the handler's ProcessRequest to start the process. This implementation begins by calling the method FrameworkInitialize(), which builds the control trees for the page. This is a protected and virtual member of TemplateControl class, class from which page itself derives.

Next the processRequest() makes page transits various phases: initialization, loading of viewstate and postback data, loading of page's user code and execution postback server-side events. Then page enters in render mode, the viewstate is updated and HTML generated is sent to the output console. Finally page is unloaded and request is considered completely served.

Page Execution Stages

The first stage in the page life cycle is initialization. This is fired after the page's control tree has been successfully created. All the controls that are statically declared in the .aspx file will be initialized with the default values. Controls can use this event to initialize some of the settings that can be used throughout the lifetime of the incoming web request. Viewstate information will not be available at this stage.

After initialization, page framework loads the view state for the page. Viewstate is a collection of name/value pairs, where control's and page itself store information that is persistent among web requests. It contains the state of the controls the last time the page was processed on the server. By overriding LoadViewState() method, component developer can understand how viewstate is restored.
Once viewstate is restored, control will be updated with the client side changes. It loads the posted data values. The PostBackData event gives control a chance to update their state that reflects the state of the HTML element on the client.

At the end of the posted data changes event, controls will be reflected with changes done on the client. At this point, load event is fired.

Key event in the life cycle is when the server-side code associated with an event triggered on the client. When the user clicks on the button, the page posts back. Page framework calls the RaisePostBackEvent. This event looks up for the event handler and run the associated delegate.

After PostBack event, page prepares for rendering. PreRender event is called. This is the place where user can do the update operations before the viewstate is stored and output is rendered. Next stage is saving view state, all the values of the controls will be saved to their own viewstate collection. The resultant viewstate is serialized, hashed, base24 encoded and associated with the _viewstate hidden field.

Next the render method is called. This method takes the HtmlWriter object and uses it to accumulate all HTML text to be generated for the control. For each control the page calls the render method and caches the HTML output. The rendering mechanism for the control can be altered by overriding this render method.

The final stage of the life cycle is unload event. This is called just before the page object is dismissed. In this event, you can release critical resources you have such as database connections, files, graphical objects etc. After this event browser receives the HTTP response packet and displays the page.

Generics in C#

Generics
Generics are a new feature in version 2.0 of the C# language and the common language runtime (CLR). Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations, as shown here:

Example

public class GenericList<T>
{
void Add(T input) { }
}
class TestGenericList
{
private class ExampleClass { }
static void Main()
{
// Declare a list of type int
GenericList<int> list1 = new GenericList<int>();

// Declare a list of type string
GenericList<string> list2 = new GenericList<string>();

// Declare a list of type ExampleClass
GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
}
}


Generics Overview
Use generic types to maximize code reuse, type safety, and performance.

The most common use of generics is to create collection classes.

The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible in place of classes such as ArrayList in the System.Collections namespace.

You can create your own generic interfaces, classes, methods, events and delegates.

Generic classes may be constrained to enable access to methods on particular data types.

Information on the types used in a generic data type may be obtained at run-time by means of reflection.

Labels:

Nullable types in C#

Nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying value type, plus an additional null value. For example, a Nullable, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable can be assigned the values true or false, or null. The ability to assign null to numeric and Boolean types is particularly useful when dealing with databases and other data types containing elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.

Example

class NullableExample
{
static void Main()
{
int? num = null;
if (num.HasValue == true)
{
System.Console.WriteLine("num = " + num.Value);
}
else
{
System.Console.WriteLine("num = Null");
}

//y is set to zero
int y = num.GetValueOrDefault();

// num.Value throws an InvalidOperationException if num.HasValue is false
try
{
y = num.Value;
}
catch (System.InvalidOperationException e)
{
System.Console.WriteLine(e.Message);
}
}
}


Nullable Types Overview
Nullable types have the following characteristics:

Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)

The syntax T? is shorthand for System.Nullable, where T is a value type. The two forms are interchangeable.

Assign a value to a nullable type in the same way as for an ordinary value type, for example int? x = 10; or double? d = 4.108;

Use the System.Nullable.GetValueOrDefault property to return either the assigned value, or the default value for the underlying type if the value is null, for example int j = x.GetValueOrDefault();

Use the HasValue and Value read-only properties to test for null and retrieve the value, for example if(x.HasValue) j = x.Value;

The HasValue property returns true if the variable contains a value, or false if it is null.

The Value property returns a value if one is assigned, otherwise a System.InvalidOperationException is thrown.

The default value for a nullable type variable sets HasValue to false. The Value is undefined.

Use the ?? operator to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type, for example int? x = null; int y = x ?? -1;

Nested nullable types are not allowed. The following line will not compile: Nullable<Nullable<int>> n;

Labels:

Thursday, 22 May 2008

An Architectural Introduction to Web Parts and ASP.NET

Web Part Framework
The Web Part Framework is the basis for extensibility in Windows SharePoint Services. It allows developers to write custom components that plug into the SharePoint infrastructure by encapsulating web services and enterprise data as Web Parts.
Windows SharePoint Services as a whole is based heavily on .NET technologies:
· ASP.NET instead of ISAPI for base page execution
· CLR based server object model for programmatic access to SharePoint data
· XML Web services-based access of SharePoint data from remote machines
In keeping with this investment in .NET technologies, the Web Parts Framework is also based entirely on ASP.NET:
· Web Part pages are ASP.NET pages.
· Web Parts are ASP.NET custom controls.
The fundamental notion in the Web Part Framework is that of a Web Part Page. A Web Part Page is essentially a scalable version of the Digital Dashboard. It is a container of Web Parts. A Web Part Page uses Windows SharePoint Services to store per-user views of the page, which enables powerful customizations on a user-by-user basis.

What Are Web Parts?
Web Parts are customizable plug and play components that empower information workers to create personalized user interfaces by simply dragging and dropping them onto a web page. Web parts allow customization at both design time and at run time. In fact, Web Parts blur the distinction between design time and run time:
· Web page authors use FrontPage 2003 to work with Web Parts by dragging and dropping them to a Web Part Page, and then customizing them using the developer enabled properties. In this sense, Web Parts are similar to design time controls.
· Web Parts also enable web page authors to use the browser as their authoring platform. Windows SharePoint Services provides a browser-based interface to design a SharePoint based site.
· The end user can customize a Web Part Page at run time by modifying the properties of each individual web part. The page author can designate which web parts can be customized or not by grouping them into “zones” and setting the appropriate properties on the zone using FrontPage 2003.
From the point of view of a developer, a web part is simply a specialized ASP.NET server control. To create a new Web Part, you create an ASP.NET custom control. However, unlike standard ASP.NET controls, which developers add to Web form pages at design time, Web Parts are intended to be added to Web Part Pages either by authors at design time, or by users at run time.
Note: Developers can also use Web Parts in “regular” ASP.NET pages, but in doing so, the developer loses the advantages of integration with Windows SharePoint Services.

Web Parts and Windows SharePoint Services
Web Parts rely heavily on Windows SharePoint Services to support:
· Creation of new sites and new pages
· Management of the user roster for a site
· Storage of Web Part customizations, including shared and personal property settings
· Administration of site backups and storage limits
· A scalable architecture that can handle thousands of sites and millions of users
· Assignment of users to customizable site groups
In turn, SharePoint Products and Technologies rely on Web Parts to provide configurable and extensible user interfaces.

Composition of a Web Part
A Web Part is composed of the following entities:
· The Web Part description file (.dwp) is a portable container of default and personalized property values for the Web Part.
· The Web Part assembly file (.dll) contains the logic and code for the Web Part, and is installed on the server running Windows SharePoint Services.
· Resource files that support the Web Part; these are also stored on the server.
· Tables in the Windows SharePoint Services database are used to store current values of the Web Part properties.
Windows SharePoint Services has been designed from the ground-up to be a powerful collaborative platform. It is possible and indeed commonplace for your web site to contain multiple instances of the same Web Part. Each instance would conceivably have a different set of properties.
Regardless of the number of instances of the Web Part, there is only one Web Part assembly file. Any instance-specific customizations are stored in the .dwp file and there exist as many .dwp files for a Web Part as there are instances of that part.

Brief Overview of ASP.NET
As we noted in the Introduction, the Web Part infrastructure is based on .NET technologies, specifically ASP.NET. Web Parts themselves are specialized ASP.NET custom controls and they reside on a Web Part Page, which is a specialized ASP.NET web forms page.
For readers that may not be familiar with these technologies, this section gives a very brief overview the main concepts. The reader should refer to many excellent books and articles on this topic.

ASP.NET Web Applications
ASP.NET is part of the .NET Framework and is the core technology for developing web applications and XML Web Services. ASP.NET pages run on the server and generate markup such as HTML, WML, or XML that is sent to a desktop or mobile browser. ASP.NET pages use a compiled, event-driven programming model that improves performance and enables separating the application logic and user interface. ASP.NET pages and ASP.NET XML Web services files contain server-side logic (as opposed to client-side logic) written in Visual Basic .NET, C# .NET, or any .NET-compatible language. Web applications and XML Web services take advantage of the features of the common language runtime, such as type safety, inheritance, language interoperability, versioning, and integrated security.
An ASP.NET web application is defined as all files, pages, handlers, modules, and executable code that you can invoke or run in the scope of a given virtual directory (and its subdirectories) on an IIS server. Typical ASP.NET applications consist of the following:
· One or more web forms pages – which are text files with an .aspx extension. These pages typically consist of HTML markup which declares the controls on the page and specifies their formatting and layout attributes.
· One or more code files; you can developed in develop code C#, Visual Basic, J#, Jscript, etc. The code files contain the web application’s logic, including control event handling, postback handling, etc. The code files are tightly bound to the aspx files and are referred to as “code behind”.
· A Global.asx file to deal with session and application startup and clean-up logic. This file is optional.
· A Web.config file used to store configuration settings. This file is optional, and is new for ASP.NET


Web Forms Pages and Server Controls
Let’s look at a web forms page in more detail. In doing so, we will gain an understanding of ASP.NET server controls and code behind files.
Note This section provides a walkthrough for building an ASP.NET web application so that the reader can gain an understanding of the platform technologies that form the basis for web part pages. However, it is not possible to run arbitrary ASP.NET code within a web part page; specifically, you cannot insert the code presented in this section inside a web part page.
Web forms are ASP.NET pages which use ASP.NET server controls. Server controls are a set of built-in controls which are similar to Microsoft Visual Basic controls – essentially, prewritten pieces of code which you can drag and drop into your application. Just like Visual Basic controls, ASP.NET server controls are event driven; the developer’s task is to write code that handles events raised by the controls. This code appears in the code-behind file of the corresponding aspx file.
ASP.NET provides two sets of built-in server controls:
· HTML controls, which provide a 1-1 mapping to HTML elements
· Web controls, which provide prepackaged UI functionality such as text boxes, data grids, labels, etc. In addition, a class of Web controls, called Validation controls, are used to validate user input on a form (usually avoiding a round-trip to the server)
Let us now examine a sample web application. Below is a screenshot of the application:
The user types his name into the text box and clicks on the button labeled ClickMe. The application displays the text: “Hello World! This is ”.
Apart from the configuration files (global.asx, web.config), this application consists of 2 main files: Webform1.aspx – which is the web forms file, and WebForm1.aspx.cs, which is the code behind file.
Shown below is the WebForm1.aspx file:
File WebForm1.aspx

1. <%@ Page language="c#" Codebehind="WebForm1.aspx.cs"
AutoEventWireup="false" Inherits="TestWebApp.WebForm1" %>
2.
3.
4.
5. WebForm1
6.
7.
8.
9. content="http://schemas.microsoft.com/intellisense/ie5">
10.
11.
12.

13.
14.

15.
16. Name
17.

18. Text="ClickMe">
19.

20. Width="272px">
21.

22.

23.
24.

This form is strictly markup and no code. All the code required for processing the form appears in a separate file, called the “code-behind” file. This is one of the major innovations in ASP.NET; it separates the presentation from the logic, thus solving one of the major problems with ASP – ASP code was hard to maintain because it was interspersed with HTML markup.
· Line 1 identifies the code behind file to be webform1.aspx.cs. With this directive, the framework knows where to look for when it needs event handlers to process the aspx file.
· Line 12 begins the
tag, but with the runat attribute set to “server”.
· Lines 13, 15, 18, and 20 declare the Web controls used on this page. They are, respectively, a text box, a label, a button, and another label.
For each control, its id is declared, as are some style and layout parameters.

Shown below is the Code-Behind file for this form:
File: WebForm1.aspx.cs

1. using System;
2. using System.Collections;
3. using System.ComponentModel;
4. using System.Data;
5. using System.Drawing;
6. using System.Web;
7. using System.Web.SessionState;
8. using System.Web.UI;
9. using System.Web.UI.WebControls;
10. using System.Web.UI.HtmlControls;

11. namespace TestWebApp
12. {
13. public class WebForm1 : System.Web.UI.Page
14. {
15. protected System.Web.UI.WebControls.TextBox TextBox1;
16. protected System.Web.UI.WebControls.Label Label1;
17. protected System.Web.UI.WebControls.Button Button1;
18. protected System.Web.UI.WebControls.Label Label2;
19. private void Page_Load(object sender, System.EventArgs e)
20. {
21. // Put user code to initialize the page here
22. }

23. override protected void OnInit(EventArgs e)
24. {
25. InitializeComponent();
26. base.OnInit(e);
27. }

28. private void InitializeComponent()
29. {
30. this.Button1.Click += new
31. System.EventHandler(this.Button1_Click);
32. this.Load += new System.EventHandler(this.Page_Load);
33. }

34. private void Button1_Click(object sender, System.EventArgs e)
35. {
36. string Temp;
37. Temp = "Hello World!" + "This is " + TextBox1.Text;
38. Label2.Text = Temp;
39. }
40. }
41. }

The form is represented by the class WebForm1, which is derived from the Page class in the System.Web.UI namespace. The “Inherits” of the @Page directive (in line 1 of WebForm1.aspx file) establishes the binding between WebFrom1 class and the aspx page.
· Lines 15 – 18 declares the controls used in the form.
Note that from the perspective of code, these server controls are simply C# classes; these classes appear in the System.Web.UI.WebControls namespace.
· Lines 28 – 33 declares the WebForms1::InitializeComponent method to add a new event handler for handling “click” events on Button1.
· Line 33 adds another event handler for the Load event for this page.
· Lines 34 – 39 declares the Button1_Click() method that contains the real logic in our web application. This method builds the output string by taking the text from TextBox1 inline 38 and setting this string to be the text of Label2. Since Button1_Click() method has been designated as the event handler for the “click” event on Button1 in line 32, this code gets invoked when the user clicks the button.
ASP.NET Custom Controls
The ASP.NET server control infrastructure essentially provides a code-reuse mechanism. It enables the writing of reusable UI entities which you can incorporate in a page. At runtime, the control provides ASP.NET with HTML describing its appearance.
ASP.NET ships with a rich library of server controls. These controls address the needs of many common web design tasks. Rich as the control library is, there are still cases where a web developer is unable to find a control that precisely suits her purposes. It is desirable therefore, there be a way to create custom, reusable UI objects that developers can use in Web Forms.
To address such situations, ASP.NET provides the ability to write your own controls. They fall into two broad categories:
· User Controls provide a simple and fast method for reusing your presentation code. They are simply HTML or ASP.NET code saved in a file with an .ascx extension. However, you cannot directly call a user control (as .aspx pages can). You have to include them within an aspx page. User controls can contain almost any element that a web forms page can contain. User controls are an evolution of Server Side Includes (SSI) in ASP.
· Custom Controls are .NET components which can produce HTML to render themselves in Web Forms.
This section will focus on the Custom Controls. This is because a Web Part is an ASP.NET custom control.
An ASP.NET server control is a class that derives directly or indirectly from System.Web.UI.Control. The following two classes are the base classes for ASP.NET server controls:
· System.Web.UI.Control: This class defines the properties, methods, and events common to all ASP.NET server controls. It does not have any user interface (UI) specific features.
· System.Web.UI.WebControls.WebControl: This class derives from Control and provides additional properties and methods for UI functionality (such as ForeColor, BackColor, Font, BorderStyle, etc). In fact, most of the built in ASP.Net server controls derive from this class.
Shown below is the code for a simple ASP.NET custom control.
1. using System;
2. using System.Web.UI;
3. using System.Web.UI.WebControls;
4. using System.ComponentModel;

5. namespace MyCustomControls
6. {
7. [DefaultProperty("Greeting"), ToolboxData("<{0}:ComputerName
runat=server>")]
8. public class ComputerName : System.Web.UI.WebControls.WebControl
9. {
10. private string _Greeting;
11. [Bindable(true), Category("Appearance"), DefaultValue("")]
12. public string Greeting
13. {
14. get
15. {
16. return _Greeting;
17. }
18. set
19. {
20. _Greeting = value;
21. }
22. }
23. protected override void Render(HtmlTextWriter output)
24. {
25. output.Write(" "+ this.Greeting + "
" +
"The name of this server is " +
System.Windows.Forms.SystemInformation.ComputerName +
"
");
26. }
27. }
28. }

The name of the control is “ComputerName”; this control has one property, called Greeting. The control gets the name of the server and appends it to the Greeting, and produces HTML to display this text. For example, if the server name is “MyServer” and Greeting is set to the string “Hello”, then it produces the text: “Hello. The name of this server is MyServer”
· Line 5 declares the namespace, “MyCustomControls”. Every control (indeed, every .NET component) belongs to a namespace.
· Line 7 defines the design-time and run-time metadata for the control, required for (among other things) displaying the control at design time, data binding, displaying property sheets, etc.
· Line 8 declares the class named “ComputerName” for our control. A custom control is implemented as a class. This class is typically derived from the WebControl class provided by the framework.
· Line 11 defines the properties for the control. At design time, the property sheet editor in Visual Studio.net 2003 requires metadata for the property, such as its category, default value, etc.
· Lines 12 – 22 define the accessors for the Greeting property of our control.
· Lines 23 – 26 declares the Render method (which is an overridden method of the WebControl class) used to produce HTML.
· Line 25 uses an HtmlTextWriter object called “output” to produce HTML tags. This method takes the “Greeting” property and concatenates it with the ComputerName property of the SystemInformation class and produces this string, along with some HTML tags.
Below is an aspx page that uses this control; since this control doesn’t expose any events, there is no need for writing event handlers in the code-behind file.
1. <%@ Page language="c#" Codebehind="WebForm1.aspx.cs"
AutoEventWireup="false" Inherits="TestWebApp.WebForm1" %>
2. <%@ Register TagPrefix="cc1" Namespace="MyCustomControls"
Assembly="MyCustomControls" %>
3.
4.
5.
6. WebForm1
7. name="GENERATOR">
8.
9.
10. name="vs_targetSchema">
11.
12.
13.
14. runat="server" Height="22px" Greeting="Welcome">
15.

16.
17.

· Line 2 uses the @Register directive. This contains the namespace and assembly name for the custom control. It uses the TagPrefix attribute to prevent name collisions. For instance, if somebody else creates a control whose name is also “ComputerName”, then these two controls are distinguished by the different tag prefixes (such as cc1 and cc2).
· Line 14 contains the markup for inserting the control into the page. The syntax and semantics of this markup is the same for a custom control and a built-in control (see the previous section for details).
When you run this page with the Greeting property set to “Welcome”, the output looks like this:
Creating Custom Web Parts
As mentioned before in this document, Web Parts are ASP.NET custom controls. Microsoft Visual Studio.net 2003 is an excellent environment for building and debugging ASP.NET custom controls. Developers can use it for building Web Parts as well.
There are two project templates you can use when building a Web Part using Microsoft Visual Studio.net 2003:
· Use the Web Control Library project: This project template comes with Microsoft Visual Studio.net 2003 which developers can use for building any ASP.NET controls, including Web Parts.
· Use the Web Part Library project: This project template is available as a free download from Microsoft that is optimized for building Web Parts.
In the rest of this section, we will use the Web Part Library project template. There are several advantages to using the Web Part Library template:
· Automatically adds a reference to the Microsoft.SharePoint.dll file, which is the assembly that contains the set of classes required to build Web Parts.
· Creates a Web Part class file.
· Creates a Web Part description (.dwp) file.
· Creates a Web Part manifest file, which is an XML file containing metadata used by stsadm.exe during the deployment of Web Parts.
· Adds new instances of the above files to the project by a simple right click; you can also add consumer and provider Web Part files and Tool Part files to the project.
Note: each of the above should be manually accomplished when using the Web Control Library project.
Installing the Web Part Library Template
The Web Part Library template is available for download at http://microsoft.com/downloads/details.aspx?FamilyId=14D5D92F-C3A6-407C-AAD7-B8C41A4991BE&displaylang=en.
To add the Web Part Library template to your Microsoft Visual Studio.net 2003 installation, follow these steps:
1. Download the Web Part Library templates and run the executable.
2. The Setup Wizard starts. Click Next to install the package.
3. Select the programming languages for which you want to install the templates and then click Next.
4. In the text box provided, type the location of the Windows SharePoint Services assembly in the file system and click Next.
5. The Confirm Installation page appears. Click Next to continue.
6. The Installation Complete page appears. Click Close to close the Setup Wizard.
Creating and Deploying a Web Part
To create a basic Web Part, follow these steps:
1. Create a new project in Microsoft Visual Studio.net 2003 based on the Web Part Library template.
2. Write code for the Web Part.
3. Strongly name the Web Part.
4. Create a Web Part description file (dwp).
5. Copy the Web Part assembly and the dwp file into the web application directory on the machine running Windows SharePoint Services.
6. Identify the Web Part as a safe control.
7. Import the Web Part into a Web Part Page or put the Web Part into the virtual server library.
The details of each of these steps are beyond the scope of this paper; we refer the reader to the following white papers:
· “A Developer’s Introduction To Web Parts”
· “Packaging and Deploying Web Parts for Windows SharePoint Services”
Both are available for download at http://msdn.microsoft.com/library/default.asp?url=/downloads/list/SharePoint.asp.
In this paper, we will examine the sample code for a simple Web Part and look at a dwp file that will accompany it.
Example: A Sample Web Part
The following code illustrates a simple Web Part which has a text box and a button; when you click on the button, the string in the text box is appended to the title of the Web Part.
1. using System;
2. using System.ComponentModel;
3. using System.Web.UI;
4. using System.Web.UI.WebControls;
5. using System.Xml.Serialization;
6. using Microsoft.SharePoint;
7. using Microsoft.SharePoint.Utilities;
8. using Microsoft.SharePoint.WebPartPages;
9. using System.Web.UI.HtmlControls;
10. using System.Runtime.InteropServices;

11. namespace WebPartLibrary1
12. {
13. [DefaultProperty("Text"),
ToolboxData("<{0}:WebPart1 runat=server>"),
XmlRoot(Namespace="WebPartLibrary1")]
14. public class WebPart1 :
Microsoft.SharePoint.WebPartPages.WebPart
15. {
16. private const string defaultText = "New Web Part";
17. private string text=defaultText;

18. // declare HTML controls used by this web part
19. HtmlButton _myButton;
20. HtmlInputText _myTextBox;

21. // Event handler for _myButton control; it gets the string in
// the text box & appends it to the custom property "Text" &
// sets this as the title of the web part
22. public void _myButton_Click (object sender, EventArgs e)
23. {
24. this.Title = _myTextBox.Value + "'s " + this.Text;
25. }

26. [Browsable(true),Category("Miscellaneous"),
DefaultValue(defaultText),
WebPartStorage(Storage.Personal),
FriendlyName("Text"),Description("Text Property")]
27. public string Text
28. {
29. get
30. {
31. return text;
32. }
33. set
34. {
35. text = value;
36. }
37. }

38. // override Web.UI.Controls.CreateChildControls method
39. protected override void CreateChildControls()
40. {
41. // create _myButton control and add event handler
42. _myButton = new HtmlButton();
43. _myButton.InnerText = "Add your Name to title";
44. _myButton.ServerClick += new EventHandler(_myButton_Click);
45. Controls.Add(_myButton);
46. _myTextBox = new HtmlInputText();
47. _myTextBox.Value = "";
48. Controls.Add(_myTextBox);
49. }

50. /// Render this Web Part to the output parameter specified.
51. protected override void RenderWebPart(HtmlTextWriter output)
52. {
53. _myTextBox.RenderControl(output);
54. _myButton.RenderControl(output);
55. }
56. }
57. }

You may notice that this code looks like the code shown for ASP.NET the custom control in a previous section. This should come as no surprise because Web Parts are ASP.NET custom controls.
However, there exist several differences.
The first is in Line 14:
· The Web Part class derives from Microsoft.SharePoint.WebPartPages.WebPart class, as opposed to a stock ASP.NET control, which derives from one of System.Web.UI.Control or System.Web.UI.WebControls.WebControl.
· However, the WebPart class itself derives from System.Web.UI.Control class and this is what ties a Web Part into the entire ASP.NET control infrastructure. To the features of a stock ASP.NET control, the Web Part class adds the following:
· Creates the title bar, border etc., around the control, which users can customize by setting properties and applying themes.
· Handles interactions with the WebPartPage and WebPartZone classes to support adding, moving, hiding, deleting, connecting, and personalizing Web Parts on a page. This is what “plugs” a Web Part into the Windows SharePoint Services infrastructure.
· Provides a set of common properties such as Title, Height, Width, FrameState, etc.
The second difference is in Line 51.
· When rendering an ASP.NET control, you typically override the Render method of the base class; however, the WebPart class has sealed the Render method. Developers should override the special RenderWebPart method provided by the WebPart class.
The rest of the code show above is straightforward ASP.NET control code:
· Lines 19 and 20 create HTML text controls used in this web part (an input text and a button control)
· Lines 21 - 25 define the event handler for the button click event. This handler simply takes the value in the text box, appends this to the value of the custom property called “Text”, and sets this as the new title. Thus if the Text Property is “New Web Part” and the string “Ralph” is typed in the input text box, then the button click will set the new title of the Web Part to “Ralph’s New Web Part”.
· Lines 26 - 37 define the accessors for the Text custom property.
· In lines 38 - 49, we override the CreateChildControls method of the base class to initialize the controls in this Web Part. The controls are added to the collection of child controls for this Web Part class. Also, we add the click event handler defined in lines 21-25 to the HtmlButton’s ServerClick event.
Rendering the Web Part at Design Time
FrontPage 2003 provides a design time preview of Web Parts on a Web Part Page at design time. The developer can exercise precise control over this design time rendering. This is done by implementing the IDesignTimeHtmlProvider interface in the Web Part. This interface has a single method, called GetDesignTimeHtml, which returns the HTML string used to render the Web Part. Design tools such as FrontPage 2003 which leverage Windows SharePoint Services, check to see if this interface is implemented; if it is, then they call the GetDesignTimeHtml method for rendering. Otherwise, they use the default rendering for that Web Part.
Creating a Web Part Description File (dwp)
The Windows SharePoint Services infrastructure uses the Web Part description file which contains metadata about the Web Part.
Shown below is the dwp file for the Web Part created in the previous section:
1.
2.
3. New Web Part
4. WebPart1.
5. WebPartLibrary1, Version=1.0.0.0, Culture=Neutral,
PublicKeyToken=334fd085a590fb9f

6. WebPartLibrary1.WebPart1
7.


As you can see, the dwp is an XML file. The root element of this file is the element, and it contains, among others, the following tags:
· specifies the default title of the Web Part <br />· <description> specifies the pop up description for the Web Part which FrontPage 2003 and the browser displays. <br />· <assembly> specifies the name of the assembly that contains the implementation for this Web Part. <br />· <typename> specifies the class within the assembly which implements the Web Part. This is required because an assembly can implement more than one Web Part and/or other ASP.NET controls. Notice how the value of the TypeName tag corresponds to the namespace declaration (line 11) and class declaration (line 14) shown in the previous section. <br />Note You can export dwp files in FrontPage 2003, using Tools/Save Web Part to/File… <br /><a name="_Toc52669482">Deploying the Web Part</a> <br />You can deploy a Web Part in two different ways: <br />· Place it in one of the Windows SharePoint Services Web Part Libraries – the virtual server library, site library, or the online library. This makes it available to all pages in the site. <br />· Import it into a specific page. This makes the Web Part available only to that page and it will not appear in any gallery. <br /><a name="_Toc52669483">Deploying in a Windows </a>SharePoint Services Library <br />Before deploying the Web Part into a Windows SharePoint Services Library, you must build a Web Part Package. A Web Part Package is a cabinet (.cab) file that contains the following items: <br />· Manifest.xml <br />· .dwp files <br />Note: When using the Web Part Library template for Microsoft Visual Studio.net 2003, it automatically creates the manifest.xml and dwp files for you. <br />· Web Part assemblies: one or more .NET assemblies and are the result of building your Web Part Library solution <br />· Class resource files contain bitmaps and other resources required for your Web Part. <br />The details of the structure of manifest.xml, and the modalities of building a CAB file are outside the scope of this paper. For details, please see the white paper entitled “Packaging and Deploying Web Parts for Microsoft Windows SharePoint Services” at <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnspts/html/sharepoint_DeployingWebParts.asp">http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnspts/html/SharePoint_DeployingWebParts.asp</a>. <br />Once you have a CAB file, you can use the stsadm.exe tool on the server running Windows SharePoint Services to add the Web Part to the virtual server library. The typical command line for using stsadm.exe to add a Web Part looks like below: <br />stsadm.exe –o addwppack –filename path_to_CAB_file <br /><a name="SW9"> </a> <br />The stsadm.exe tool is typically available in <br /><drive>:\Program Files\Common Files\Microsoft Shared\web server extensions\60\BIN <br />For more details on using stsadm.exe tool, see the “Packaging and Deploying Web Parts for Microsoft Windows SharePoint Services” white paper referenced above. <br />Using the stsadm.exe tool deploys the Web Part into the virtual server library and you can use with FrontPage 2003 or the Web Browser interface. You can make any Web Part in the virtual server library available in the site library. For more details on managing Web Parts in these libraries, see “FrontPage 2003: <a href="http://www.sharepointcustomization.com/resources/whitepapers/webpartdocs/wp_libraries.doc">Working with Web Part Libraries</a>”. <br /><a name="_Toc52669484">Importing the Web Part into a Specific Page</a> <br />You can also simply import a Web Part onto a page. The process of import does not add the Web Part to the Virtual, Site, or Online libraries; it is just available on a given page. Before you can import a Web Part onto a page, you must perform the following tasks on the machine running Windows SharePoint Services: <br />1. Copy the Web Part assembly to the <drive>:\inetpub\wwwroot\bin folder. <br />2. Register the Web Part as a safe control. Do this by editing the web.config file, located in the <drive>:\inetpub\wwwroot folder. For our sample Web Part, this involves adding the following lines under the <configuration>/<sharepoint>/<safecontrols> block: <br /><SafeControl Assembly="WebPartLibrary1, Version=1.0.0.0, <br /> Culture=Neutral, PublicKeyToken=334fd085a590fb9f" <br /> Namespace="WebPartLibrary1" TypeName="*" Safe="True" /> <br />3. Make the dwp file for the Web Part available for the users that want to import this Web Part. <br />Assuming these steps are performed, the Web Part can be imported onto a page using FrontPage 2003 using the following steps: <br />1. Bring up the Web Parts task pane: View/Taskpane and select “Web Parts” from the dropdown list of available task panes. <br />2. Under Add Web Parts, click Import. <br />3. Browse to or type in the location of the .dwp file for the Web Part you want to import. <br />4. Click “Upload”. The Web Part now appears on the task pane. <br />You can now drag and drop the part onto the page. <br /><a name="_Toc52669485">Using the Web Part in FrontPage 2003</a> <br />In this section, we will assume that our sample Web Part is available in the Virtual Server Library of the Windows SharePoint Services installation. <br />Using this Web Part is no different from using any other Web Part. To use a Web Part, follow these steps: <br />1. Open the site you wish to work with in FrontPage 2003. For the purposes of this section, we will assume the site is located at the URL: <a href="http://myserver/my-workgroup">http://myserver/my-workgroup</a>. <br />2. Click on Data/Insert Web Parts to open the Web Parts taskpane in FrontPage 2003. <br />3. Click on Virtual Server Gallery to display the available Web Parts. You should see the sample Web Part available there; its title is New Web Part. <br />Below is a screenshot of the task pane: <br />4. Drag and drop this Web Part into an appropriate zone in your web page. For the purposes of illustration, let us assume that we have dragged the Web Part into the default.aspx page of a Windows SharePoint Services site created using the Team Site template. <br />5. Save the page and run it in the browser by typing the appropriate URL. We have used the URL <a href="http://myserver/default.aspx">http://myserver/default.aspx</a>. <br />6. Locate the Web Part you just added (it should be titled “New Web Part”). <br />7. Type your name in the text box, and click on Add your Name to title button. The title will change to (assuming the name you typed was Murali) “Murali’s New Web Part”. <br />Below is a screenshot of this: <br />Recall that this Web Part has a custom property called Text. Refer to the Web Part code in “Example: A Sample Web Part”. <br />Note the following: <br />· Line 22 – 25 specifies that the event handler for the button click event on the Add your Name to title button take the value of the Text property, append it to the string typed in the text field, and set this as the value of the title. <br />· Lines 26 – 37 implements the custom property and specifies that this property has to be put under the category “Miscellaneous”. <br />To manipulate this property in FrontPage 2003, follow these steps: <br />1. In the Web Part properties dialog box, notice the new category called Miscellaneous. Expanding this category shows a property called Text and a text box to enter the value for it. FrontPage 2003 automatically displays a text box to enter the value of this property because the data type of this property is string (line 27 of the code in “Example: A Sample Web Part”) <br />2. Type “Fancy Web Part” as the new value of this property. <br />3. In FrontPage 2003, right click on our example Web Part and select Web Part Properties in the pop-up menu. <br />Below is a screenshot of how this should look: <br />4. Click OK, save changes and run the page in the browser by typing the appropriate URL. We have used the URL <a href="http://myserver/default.aspx">http://myserver/default.aspx</a>. <br />5. Locate our example Web Part (it title should be “New Web Part”). <br />6. Type your name in the text box, and click on Add your Name to title button. The title will change to (assuming that the name you typed was Murali) “Murali’s Fancy Web Part”. <br />Below is a screenshot of this: <br />Note By default, the custom properties you create and specify as browsable are automatically displayed in the default property pane, making their use transparent to the user. If the default property pane isn't rich enough in functionality, you can create a custom user interface called a ToolPart to manipulate your custom properties. For information on creating a ToolPart, see the http://msdn.microsoft.com/library/default.asp?url=/library/en-us/spptsdk/html/CreateWPCustomProperties.asp. <br /><div style="clear:both; padding-bottom:0.25em"></div><p class="blogger-labels">Labels: <a rel='tag' href="http://paramesh-mstechnology.blogspot.com/search/label/Asp.Net">Asp.Net</a>, <a rel='tag' href="http://paramesh-mstechnology.blogspot.com/search/label/MOSS%202007">MOSS 2007</a>, <a rel='tag' href="http://paramesh-mstechnology.blogspot.com/search/label/webparts">webparts</a>, <a rel='tag' href="http://paramesh-mstechnology.blogspot.com/search/label/WSS%203.0">WSS 3.0</a></p> </div> </div> <p class="post-footer"> <em>posted by Paramesh Vuppala at <a class="post-footer-link" href="http://paramesh-mstechnology.blogspot.com/2008/05/architectural-introduction-to-web-parts.html" title="permanent link"> 05:09 </a></em> <a class="comment-link" href="https://www.blogger.com/comment/fullpage/post/7072778100670441917/150147073476519228"location.href=https://www.blogger.com/comment/fullpage/post/7072778100670441917/150147073476519228;><span style="text-transform:lowercase">0 Comments</span></a> <span class="item-control blog-admin pid-273648269"><a style="border:none;" href="https://www.blogger.com/post-edit.g?blogID=7072778100670441917&postID=150147073476519228&from=pencil" title="Edit Post"><img class="icon-action" alt="" src="https://resources.blogblog.com/img/icon18_edit_allbkg.gif" height="18" width="18"></a></span> </p> </div> <!-- End .post --> <!-- Begin #comments --> <!-- End #comments --> <h2 class="date-header">Wednesday, 21 May 2008</h2> <!-- Begin .post --> <div class="post"><a name="6726788715349573490"></a> <h3 class="post-title"> Evolutions and enhancements in .Net Framework </h3> <div class="post-body"> <div> <div style="clear:both;"></div>Evolutions and enhancements in .Net Framework<br /><br />.Net Framework 1.1<br /><a href="http://msdn.microsoft.com/en-us/library/9wtde3k4.aspx">http://msdn.microsoft.com/en-us/library/9wtde3k4.aspx</a><br /><br />.Net Framework 2.0<br /><a href="http://msdn.microsoft.com/en-us/library/t357fb32.aspx">http://msdn.microsoft.com/en-us/library/t357fb32.aspx</a><br /><br />.Net Framework 3.0<br /><a href="http://msdn.microsoft.com/en-us/library/bb822048.aspx">http://msdn.microsoft.com/en-us/library/bb822048.aspx</a><br /><br />.Net Framework 3.5<br /><a href="http://msdn.microsoft.com/en-us/library/bb332048.aspx">http://msdn.microsoft.com/en-us/library/bb332048.aspx</a><div style="clear:both; padding-bottom:0.25em"></div><p class="blogger-labels">Labels: <a rel='tag' href="http://paramesh-mstechnology.blogspot.com/search/label/.Net">.Net</a>, <a rel='tag' href="http://paramesh-mstechnology.blogspot.com/search/label/.Net%20Framework">.Net Framework</a></p> </div> </div> <p class="post-footer"> <em>posted by Paramesh Vuppala at <a class="post-footer-link" href="http://paramesh-mstechnology.blogspot.com/2008/05/evolutions-and-enhancements-in-net.html" title="permanent link"> 00:04 </a></em> <a class="comment-link" href="https://www.blogger.com/comment/fullpage/post/7072778100670441917/6726788715349573490"location.href=https://www.blogger.com/comment/fullpage/post/7072778100670441917/6726788715349573490;><span style="text-transform:lowercase">0 Comments</span></a> <span class="item-control blog-admin pid-273648269"><a style="border:none;" href="https://www.blogger.com/post-edit.g?blogID=7072778100670441917&postID=6726788715349573490&from=pencil" title="Edit Post"><img class="icon-action" alt="" src="https://resources.blogblog.com/img/icon18_edit_allbkg.gif" height="18" width="18"></a></span> </p> </div> <!-- End .post --> <!-- Begin #comments --> <!-- End #comments --> </div></div> <!-- End #main --> <!-- Begin #sidebar --> <div id="sidebar"><div id="sidebar2"> <!-- Begin #profile-container --> <div id="profile-container"><h2 class="sidebar-title">About Me</h2> <dl class="profile-datablock"> <dd class="profile-data"><strong>Name:</strong> <a rel="author" href="https://www.blogger.com/profile/12895600727596472996"> Paramesh Vuppala </a></dd> </dl> <p class="profile-link"><a rel="author" href="https://www.blogger.com/profile/12895600727596472996">View my complete profile</a></p></div> <!-- End #profile --> <h2 class="sidebar-title">Links</h2> <ul> <li><a href="http://news.google.com/">Google News</a></li> <li><a href="http://help.blogger.com/bin/answer.py?answer=41427">Edit-Me</a></li> <li><a href="http://help.blogger.com/bin/answer.py?answer=41427">Edit-Me</a></li> </ul> <h2 class="sidebar-title">Previous Posts</h2> <ul id="recently"> <li><a href="http://paramesh-mstechnology.blogspot.com/2012/11/sharepoint-2010-search-not-returning.html">SharePoint 2010 search not returning any results d...</a></li> <li><a href="http://paramesh-mstechnology.blogspot.com/2008/05/aspnet-page-life-cycle.html">ASP.Net Page Life Cycle</a></li> <li><a href="http://paramesh-mstechnology.blogspot.com/2008/05/generics-in-c.html">Generics in C#</a></li> <li><a href="http://paramesh-mstechnology.blogspot.com/2008/05/nullable-types-in-c.html">Nullable types in C#</a></li> <li><a href="http://paramesh-mstechnology.blogspot.com/2008/05/architectural-introduction-to-web-parts.html">An Architectural Introduction to Web Parts and ASP...</a></li> <li><a href="http://paramesh-mstechnology.blogspot.com/2008/05/evolutions-and-enhancements-in-net.html">Evolutions and enhancements in .Net Framework</a></li> </ul> <h2 class="sidebar-title">Archives</h2> <ul class="archive-list"> <li><a href="http://paramesh-mstechnology.blogspot.com/2008_05_21_archive.html">05/21/08</a></li> <li><a href="http://paramesh-mstechnology.blogspot.com/2008_05_22_archive.html">05/22/08</a></li> <li><a href="http://paramesh-mstechnology.blogspot.com/2008_05_27_archive.html">05/27/08</a></li> <li><a href="http://paramesh-mstechnology.blogspot.com/2012_11_15_archive.html">11/15/12</a></li> </ul> <p id="powered-by"><a href="http://www.blogger.com"><img src="http://buttons.blogger.com/bloggerbutton1.gif" alt="Powered by Blogger" /></a></p> <p id="blogfeeds">Subscribe to<br />Posts [<a target="_blank" href="https://paramesh-mstechnology.blogspot.com/feeds/posts/default" type="application/atom+xml">Atom</a>]</p> <!-- <p>This is a paragraph of text that could go in the sidebar.</p> --> </div></div> <!-- End #sidebar --> </div> <!-- End #content --> <!-- Begin #footer --> <div id="footer"><hr /> <p><!--This is an optional footer. If you want text here, place it inside these tags, and remove this comment. --> </p> </div> <!-- End #footer --> </body> </html>