31 Mart 2008 Pazartesi
CryptoCollaboration For SharePoint 2007
Project Description
CryptoCollaboration for SharePoint 2007 (works for both Microsoft Office Server 2007 as well as Windows SharePoint Services 3.0) presents a native end-to-end encryption solution targeted at SharePoint lists and their related metadata.
One of the largest tribulations that exists within current collaboration systems is the reliance on making objects security aware based solely on provided principle attributes, characteristically noticed in SharePoint through its indigenous options for security trimming the interface. While this is certainly a method that promotes some level of privacy, security, and data integrity, it does not account for data storage while information is considered in a transitional state. Furthermore, this is amplified by the fact that numerous industry regulations require that when organizational data is stored in a system as SharePoint, that it is not directly callable in plain text, however promotes a secondary layer of privacy
CryptoCollaboration is broken up into two primary segments, the CryptoCollaboration Encryption Engine (CEE) and its related SharePoint interface components. The CEE is called directly from the ECB (Edit Content Block) menu provided by the native SharePoint ListFormWebPart (your orthodox SharePoint list interface), pooling all the fields that are considered encryption worthy and encrypting or decrypting them based on user interaction. Since there are current limitations to the fields out of an arbitrary list item that can be harvested (field types such as URL’s demand that certain formats be used and therefore cannot be subject to encryption operations).
Once the encryption / decryption operations are triggered, the CEE will encrypt / decrypt the stored fields with an algorithm that the user selects out of the interface (currently supported encryption algorithms are RC2, Rijndael (AES), Triple DES, or BlowFish). All code that the CEE leverages is CLS-Compliant and 100% managed.
Adam Buenz
http://sharepointsecurity.com
Code Access Security for SharePoint 2007 Web Part Developers
Setting up SharePoint 2007 Code Access Security
In addition to my WhitePaper (Code Access Security for Administrators) I would like to explain how to setup Code Access Security for Web Part developers in SharePoint 2007.
20 Mart 2008 Perşembe
Walkthrough: Creating a Basic ASP.NET AJAX-enabled Web Part
http://msdn2.microsoft.com/en-us/library/bb861877.aspx
//
This walkthrough describes the steps for creating a basic ASP.NET AJAX-enabled Web Part that you can add to your Web Part page. The example creates a SayHello Web Part that derives from the ASP.NET 2.0 WebPart (in the System.Web.UI.WebControls.WebParts in the ASP.NET Class Library) for use in a Windows SharePoint Services 3.0 Web site.
Note:
For more information about ASP.NET Web Parts, see ASP.NET Web Parts Overview and Introducing Web Part Controls.
Prerequisites
Windows SharePoint Services 3.0
Visual Studio 2005
Step 1: Create a Web Part Project
To create an AJAX-enabled Web Part control, you start by creating a class library project in the class library in Visual Studio 2005.
To create an ASP.NET Web Part project in Visual Studio 2005
Start Visual Studio 2005.
On the File menu, point to New, and then click Project.
In Project Types, under Visual Basic or C#, select Windows.
In the Templates pane, select Class Library.
Type Sample.SayHello as the project name.
Step 2: Rename the base class and add required namespaces
After you create the project, a blank class file is displayed. You can change the default class name of Class1 to easily identify your new Web Part. In a class library project, only a few namespaces are included. You need to add two required namespaces and references to their assemblies. You must also derive the base class from System.Web.UI.WebControls.WebParts.WebPart. Then, you need to add two global variables to update the user interface (UI).
To add namespace references and shared UI components
Rename the default class by selecting Class1.cs in Solution Explorer, right-click, click Rename, and type SayHelloWebPart as the file name.
On the Project menu, click Add Reference.
In the Add Reference dialog on the .NET tab, select System.Web.Extensions and click OK.
Repeat steps 2 and 3 for the System.Web namespace.
In the references area of the class file, add a reference to System.Web.UI.WebControls and create two private variables for the UI, as shown in the following code:
C# Copy Codeusing System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
namespace Sample.SayHello
{
public class SayHelloWebPart : WebPart
{
private Label displayName;
private TextBox inputName;
}
}
Visual Basic Copy CodeImports System
Imports System.Text
Imports System.Web.UI
Imports System.Web.UI.WebControlsImports System.Web.UI.WebControls.WebParts
Public Class SayHelloWebPart
Inherits WebPart
Private displayName As Label
Private inputName as TextBox
End Class
You have now created a basic structure for the Web Part.
Step 3: Override CreateChildControls and create a button event handler.
After configuring the new class to act as a Web Part, you must override the CreateChildControls method to build the UI. You must also add a button handler to refresh the display data.
To override CreateChildControls and create a button event handler
In the SayHelloWebPart.cs file, copy and paste the following code to override the CreateChildControls method:
C# Copy Codeprotected override void CreateChildControls()
{
base.CreateChildControls();
//Fix for the UpdatePanel postback behaviour.
EnsurePanelFix();
LinkButton sayHello = new LinkButton();
UpdatePanel refreshName = new UpdatePanel();
ScriptManager scriptHandler = new ScriptManager();
displayName = new Label();
inputName = new TextBox();
//Set up control properties.
this.displayName.ID = "displayName";
this.displayName.Text = "Hello!";
this.inputName.ID = "inputName";
sayHello.ID = "sayHello";
sayHello.Text = "Say Hello";
scriptHandler.ID = "scriptHandler";
refreshName.ID = "refreshName";
refreshName.UpdateMode = UpdatePanelUpdateMode.Conditional;
refreshName.ChildrenAsTriggers = true;
//Add the EventHandler to the Button.
sayHello.Click += new EventHandler(ClickHandler);
//Add the user interface (UI) controls to the UpdatePanel.
refreshName.ContentTemplateContainer.Controls.Add(this.inputName);
refreshName.ContentTemplateContainer.Controls.Add(sayHello);
refreshName.ContentTemplateContainer.Controls.Add(this.displayName);
//The ScriptManager control must be added first.
this.Controls.Add(scriptHandler);
this.Controls.Add(refreshName);
}
Visual Basic Copy CodeProtected Overrides Sub CreateChildControls()
MyBase.CreateChildControls()
'Fix for the UpdatePanel postback behaviour.
EnsurePanelFix()
Dim sayHello As New LinkButton
Dim refreshName As New UpdatePanel
Dim scriptHandler As New ScriptManager
displayName = New Label
inputName = New TextBox
'Set up control properties.
Me.displayName.ID = "displayName"
Me.displayName.Text = "Hello!"
Me.inputName.ID = "inputName"
sayHello.ID = "sayHello"
sayHello.Text = "Say Hello"
scriptHandler.ID = "scriptHandler"
refreshName.ID = "refreshName"
refreshName.UpdateMode = UpdatePanelUpdateMode.Conditional
refreshName.ChildrenAsTriggers = True
'Add the EventHandler to the Button.
AddHandler sayHello.Click, _
New EventHandler(AddressOf ClickHandler)
'Add the user interface (UI) controsl to the UpdatePanel
refreshName.ContentTemplateContainer.Controls.Add(Me.displayName)
refreshName.ContentTemplateContainer.Controls.Add(Me.inputName)
refreshName.ContentTemplateContainer.Controls.Add(sayHello)
'The ScriptManager must be added first.
Me.Controls.Add(scriptHandler)
Me.Controls.Add(refreshName)
End Sub
Then, in the SayHelloWebPart.cs file, copy and paste the following code:
C# Copy Codeprivate void ClickHandler(object sender, EventArgs args)
{
this.displayName.Text = "Hello, "
+ this.inputName.Text.ToString() + ".";
}
Visual Basic Copy CodePrivate Sub ClickHandler(ByVal sender As Object, _
ByVal args As EventArgs)
Me.displayName.Text = "Hello, " & Me.inputName.Text & "!"
End Sub
Now you have created the basic UI and button handling event.
For ASP.NET controls that use the JavaScript _doPostBack() function to commit changes, a regular full-page postback event may occur even when the Web Part is inside an UpdatePanel control. Windows SharePoint Services 3.0 and ASP.NET AJAX cache certain form actions, which can cause a conflict between SharePoint and ASP.NET AJAX. To change this behavior, you must add code to scripts that are running in Windows SharePoint Services 3.0.
Step 4: Modify Windows SharePoint Services 3.0 scripts to change doPostBack() behavior
To modify scripts to ensure proper doPostBack() behavior
In the SayHelloWebPart.cs file, copy and paste the following code:
C# Copy Codeprivate void EnsurePanelFix()
{
if (this.Page.Form != null)
{
String fixupScript = @"
_spBodyOnLoadFunctionNames.push(""_initFormActionAjax"");
function _initFormActionAjax()
{
if (_spEscapedFormAction == document.forms[0].action)
{
document.forms[0]._initialAction =
document.forms[0].action;
}
}
var RestoreToOriginalFormActionCore =
RestoreToOriginalFormAction;
RestoreToOriginalFormAction = function()
{
if (_spOriginalFormAction != null)
{
RestoreToOriginalFormActionCore();
document.forms[0]._initialAction =
document.forms[0].action;
}
}";
ScriptManager.RegisterStartupScript(this,
typeof(SayHelloWebPart), "UpdatePanelFixup",
fixupScript, true);
}
}
Visual Basic Copy CodePrivate Sub EnsurePanelFix()
If Me.Page.Form IsNot Nothing Then
Dim fixupScript As New StringBuilder()
With fixupScript
.AppendLine("_spBodyOnLoadFunctionNames.push" & _
"(""_initFormActionAjax"");")
.AppendLine("function _initFormActionAjax()")
.AppendLine("{")
.AppendLine("if (_spEscapedFormAction == " & _
"document.forms[0].action)")
.AppendLine("{")
.AppendLine("document.forms[0]._initialAction = " & _
document.forms[0].action;")
.AppendLine("}")
.AppendLine("}")
.AppendLine("var RestoreToOriginalFormActionCore = " & _
RestoreToOriginalFormAction;")
.AppendLine("RestoreToOriginalFormAction = function()")
.AppendLine("{")
.AppendLine(" if (_spOriginalFormAction != null)")
.AppendLine(" {")
.AppendLine(" RestoreToOriginalFormActionCore();")
.AppendLine(" document.forms[0]._initialAction = " & _
"document.forms[0].action;")
.AppendLine(" }")
.AppendLine("}")
End With
ScriptManager.RegisterStartupScript(Me, _
GetType(SayHelloWebPart), "UpdatePanelFixup", _
fixupScript.ToString(), True)
End If
End Sub
Now you have modified the scripts to ensure proper postback handling.
After you've added all of your code to your Web Part project, you can build your sample Web Part and deploy it. For more information about deploying a Web Part, see Walkthrough: Creating a Basic Web Part.
See Also
Other Resources
Solutions and Web Part Packages
Tags : Add a tag Add Cancel
Community Content
Add Community Content
Avoiding Stack Overflows jsum | Edit | Show History
Please Wait
I encountered an issue when I tried to add webparts of differing types into the same web part page - the result was a stack overflow causing IE to abruptly terminate.
The problem arises when the script defined in the EnsurePanelFix method above, is inserted more than once into a page. The execution of the first script block is harmless. The execution of any subsequent block however, eventually results in a stack overflow. The reason is that the subsequent assignment to RestoreToOriginalFormActionCore is from the newly defined RestoreToOriginalFormAction (defined in the frist script block), and not the original RestoreToOriginalFormAction method.
In the subsequent execution of the script block, RestoreToOriginalFormActionCore and RestoreToOriginalFormAction are made equivalent, so the RestoreToOriginalFormAction method becomes infinately recursive.
var RestoreToOriginalFormActionCore = RestoreToOriginalFormAction; RestoreToOriginalFormAction = function() { if (_spOriginalFormAction != null) { RestoreToOriginalFormActionCore();
There are a number of ways around this, (that I can think of) but none of them are ideal. The first is to ensure that only one script block is inserted into the page, no matter how many types of your web parts are added to the page. This is done by modifying the call to RegisterStartUpScript. I found that it is the combination of the type parameter and key parameter together that determines whether the script is inserted. So I just created a base web part (MyBasePart), and used that type as the type parameter. typeof(object) also worked; I assume you can use any type that you want.
ScriptManager.RegisterStartupScript(this, typeof(MyBasePart), "UpdatePanelFixup",fixupScript, true);
Well this works if you publish all of the webparts that go into the page, but there will be issues if you also want to use web parts published by others, because depending on what type/key they used, you might still end up with more than one script block in your page. So the solution that I'm using for the time being is to define RestoreToOriginalFormAction based on what it is originally. (But this will break if the definition of RestoreToOriginalFormAction in WSS changes)
String fixupScript = @" if (typeof(_spBodyOnLoadFunctionNames) !== 'undefined'){ _spBodyOnLoadFunctionNames.push(""_initFormActionAjax""); function _initFormActionAjax() { if (_spEscapedFormAction == document.forms[0].action){ document.forms[0]._initialAction = document.forms[0].action; } } RestoreToOriginalFormAction = function() { if (_spOriginalFormAction != null) { if (_spEscapedFormAction==document.forms[0].action){ document.forms[0].action=_spOriginalFormAction; } _spOriginalFormAction=null; _spEscapedFormAction=null; document.forms[0]._initialAction = document.forms[0].action; } }; }";
I used the VS script debugger to find the original definition of RestoreToOriginalFormAction and incorporated it into the above code block. The new definition simply adds one line at the end:
document.forms[0]._initialAction = document.forms[0].action;
I removed the call to RestoreToOriginalFormActionCore. This is important because if a third party web part appears in the page after yours and again redefines the RestoreToOriginalFormAction method, there is still no possibility for recursion. i.e. RestoreToOriginalFormAction will become:
RestoreToOriginalFormAction = function() { if (_spOriginalFormAction != null) { RestoreToOriginalFormActionCore(); document.forms[0]._initialAction = document.forms[0].action; } }";
But RestoreToOriginalFormActionCore is our function, which is not recursive. The only side effect is that
document.forms[0]._initialAction = document.forms[0].action;
will be called twice in succession, but that should be harmless.
Naturally, all bets are off if you want to use your web parts with more than one web part from elsewhere.
Tags:
Please Wait
Tags : Add a tag Add Cancel
This code is causing a regular postback HotmailUser ... Noelle Mallory - MSFT | Edit | Show History
Please Wait
I've downloaded this code and built a WebPart using it with no changes. I deployed the WebPart to my MOSS 2007 site collection, and added it to a page. Clicking the LinkButton causes a full postback each time with the whole page refreshing. There's no partial rendering of the Label control.
How can I get around this?
I even tried both 1.0 and 3.5 versions of System.Web.Extensions.
Thanks.
[WolfyUK] Have you followed the steps at http://msdn2.microsoft.com/en-us/library/bb861898.aspx to configure WSS 3.0 SP1 for AJAX-enabled Web Parts?
[Noelle Mallory - MSFT] Please post questions to the MSDN Forums at http://forums.microsoft.com/msdn. You will likely get a quicker response through the forum than through the Community Content.
Tags:
Please Wait
Tags : postback (x) Add a tag Add Cancel
Multiple AJAX-enabled SharePoint Web Parts using this example WolfyUK ... kjkj3jf | Edit | Show History
Please Wait
I too have encountered issues when using this sample code in WSS 3.0 SP1 with ASP.NET AJAX Extensions 1.0.
Similar to the JavaScript overflow issues identified by jsum, you are only allowed one ScriptManager per ASP.NET page. This means that a check will need to somehow be made to see if a ScriptManager is already present on the SharePoint page before another is added by the AJAX-enabled Web Part. I haven't quite figured out the best way to achieve this yet, but catching the System.InvalidOperationException that is thrown when the second or subsequent ScriptsdddddddfsdfsdfsdfManagers are added to the Page seems to be a temporary workaround. Tags:
Please Wait
Tags : ajax (x) asp.net (x) scriptmanager (x) wss (x) Add a tag Add Cancel
Page Title gets changed when the ajax method is invoked Tragen | Edit | Show History
Please Wait
So I used the same type of architecture as listed here. However, whenever I click the method that performs the ajax call the page title gets changed to illegiable characters. Any idea why this would happen? Tags:
Please Wait
Tags : Add a tag Add Cancel
RE: Page Title gets changed when the ajax method is invoked Neil I | Edit | Show History
Please Wait
Tragen: It appears to be related to using Publishing Webs. If you try it on a regular site it'll probably work. I haven't been able to determine a workaround for that yet. If you do find one, post it here.
Redirect Reference (IIS 6.0)
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/41c238b2-1188-488f-bf2d-464383b1bb08.mspx?mfr=true
///
Redirecting a client request is one way to ensure that users get the correct page, if your site is under construction or has changed identity. You can redirect client requests to a directory on the same Web server or to a different URL.
Configuring URL and Wildcard Redirection
You can configure redirection to a URL and wildcard redirection programmatically. Redirection variables and flags allow you to specify targets and behavior by changing the HttpRedirect metabase property.
The following example shows the format of a simple redirection string.
http://DestinationURL[,Flag[s]]
Where DestinationURL can include the following redirect variables to pass portions of the original URL with the destination URL. You can use more than one variable in a single redirection string.
Variable Description Example
$S
Passes the suffix of the requested URL to the new URL. The suffix is the portion of the original URL that remains after the redirected URL is substituted.
If the EXACT_DESTINATION flag is not set, the resulting destination URL will have the name of the requested file appended as a folder name, as well as the file name itself.
If the virtual directory that is mapped to the following Web site:
http://fabrikam/Scripts
is configured to be redirected to the following exact URL:
http://fabrikam/NewScripts$S
A new request for the following URL:
http://fabrikam/Scripts/Program.exe
Would be redirected automatically to the following URL:
http://fabrikam/NewScripts/Program.exe
$P
Passes parameters (such as querystring parameters) in the original URL to the new URL, without the question mark (?).
If the virtual directory that is mapped to the following Web site:
http://fabrikam/Scripts
is configured to be redirected to the following URL:
http://fabrikam/NewScripts$P
A new request for the following URL:
http://fabrikam/Scripts/File.asp?var1=5&var2=6
Would be redirected automatically to the following URL:
http://fabrikam/NewScriptsvar1=5&var2=6
$Q
Passes parameters (such as querystring parameters) in the original URL to the new URL, including the question mark (?).
If the virtual directory that is mapped to the following Web site:
http://fabrikam/Scripts
is configured to be redirected to the following exact URL:
http://fabrikam/NewScripts$S$Q
A new request for the following URL:
http://fabrikam/Scripts/File.asp?var1=5&var2=6
Would be redirected automatically to the following URL:
http://fabrikam/NewScripts/File.asp?var1=5&var2=6
$V
Passes the requested URL, without the server name and without any parameters. To include parameters, use the $P or $Q variable with the $V variable.
If the EXACT_DESTINATION flag is not set, the resulting destination URL will have the name of the requested file appended as a folder name, as well as the file name itself.
If the virtual directory that is mapped to the following Web site:
http://fabrikam/Scripts
is configured to be redirected to the following exact URL:
http://contoso$V
A new request for the following URL:
http://fabrikam/Scripts/File.asp
Would be redirected automatically to the following URL:
http://contoso/Scripts/File.asp
Redirection Using Wildcards
You can use redirect wildcards to match any number of characters in the original URL. Begin the destination URL with an asterisk (*) and a semicolon (;), and separate pairs of wildcard characters and destination URLs with a semicolon. The following example shows the format of a redirection string that uses wildcards.
*; Wildcard1; Destination1[; Wildcard2; Destination2][, Flags]
Where WildcardN can include an asterisk (*) to match any number of characters in the original URL and pass them to DestinationN by using the $0 through $9 variables defined in the following table.
"Variable" "Description" "Example"
$0 through $9
Passes the portion of the requested URL that matches the indicted wildcard character. Wildcards must start at $0 for each Wildcard;Destination set. The EXACT_DESTINATION flag must be appended to the redirection string.
If the virtual directory that is mapped to the following Web site:
http://fabrikam/Scripts
is configured with the following redirection string:
*; /Scripts/*_in.asp; /NewScripts/$0.dll; /Scripts/*_out.asp; http://contoso/NewScripts/$0.dll
A new request for the following URLs:
http://fabrikam/Scripts/data_in.asp
http://fabrikam/Scripts/data_out.asp
Would be redirected automatically to the following respective URLs:
http://fabrikam/NewScripts/data.dll
http://contoso/NewScripts/data.dll
!
Does not allow a redirect.
This variable is useful when you want to exempt files or subdirectories from redirection when a parent directory is configured to be redirected.
If the virtual directory that is mapped to the following Web site:
http://fabrikam/Scripts
is configured to be redirected, but the following Web site:
http://fabrikam/Scripts/Commerce/Accounts
needs to be exempt, programmatically set the redirection string for the exempted folder to the following
*;!
For example, to redirect all requests for /Scripts/Filename.stm to a single file called Default.stm, and to redirect all requests for /Scripts /Filename.htm to a single file called Default.htm, use the following redirect request for the /Scripts virtual directory:
*;Filename.stm;/Default.stm/Filename.htm;/Default.htm
Using Redirection Flags
The following flags augment redirect strings of either URL or wildcard format. More than one flag is allowed. Flags are appended programmatically to the redirection string in HttpRedirect, or configured by selecting check boxes in IIS Manager.
Flag User Interface Check Box Description
EXACT_DESTINATION
The exact URL entered above
Indicates that the value provided for the destination should be considered an absolute target location.
CHILD_ONLY
A directory below this one
Alerts IIS that redirection should occur only once because the destination is in a subdirectory of the original URL. This flag avoids loops. Also, this flag instructs IIS to redirect requests only if they are to subfolders or files of the original URL.
PERMANENT
A permanent redirection for this resource
Indicates that this redirection is permanent for this resource.
TEMPORARY
Clear the A permanent redirection for this resource check box"
Indicates that this redirection is temporary for this resource.
Accessing SharePoint List Data as XML
http://www.sharepointblogs.com/dwise/archive/2008/01.aspx
///////
The other day, I found myself in need of a way to access SharePoint list data as XML but the only method available to me was a simple http GET. This is not too bad, but what can I get from SharePoint via GET? RSS is too limited and scraping the page is too painful and error-prone to even contemplate.
It turns out that there is an option available in 2007 that was carried forward from SharePoint 2003 / FrontPage days: owssvr.dll. But this isn't some forgotten FrontPage artifact, it is still a central part of SharePoint. In fact, if you pull up a list view and then view the source looking for owssvr.dll, you will see that this is the mechanism behind both the Export to Spreadsheet and Open with Access options on the list Actions menu.
How It Works
Simply put together a URL like this:
http://MyServer/[site]/_vti_bin/owssvr.dll?Cmd=Display&List={listGuid}&XMLDATA=TRUE
This will only return the fields that are defined on the default view of the list. If you need specific fields then you need to create a view with those fields and pass the View ID as well, like this:
http://.../owssvr.dll?Cmd=Display&List={listGuid}&view={viewGuid}&XMLDATA=TRUE
Specifying Fields to be Returned
There is also a Query parameter that lets you specify which fields are to be included in the resulting XML, regardless of how the view is defined. For example, if you wanted just to bring back the Title and Status Fields, you would add the field names separated by spaces (URL Encoded, of course) like "&Query=Title%20Status". If you want to return all fields, use an asterisk (*) instead of field names.
http://.../owssvr.dll?Cmd=Display&List={listGuid}&query=Title%20Status&XMLDATA=TRUE
Filtering Data
Regardless of whether you pass a view or use the default it will still use the filter defined by that view. Not bad, but you can trim this data even more by including a filter of your own using the FilterFieldn and FilterValuen arguments in the querystring. These are the same values that are passed when you use the filter options in the column headers of a view which makes it pretty easy to track down exactly what needs to be passed. Simply pull up the view that is your starting point and use the column filters to create your desired filter. Once you have it, grab all of the FilterField and FilterValue items from the querystring and add them on to yours.
http://.../owssvr.dll?Cmd=Display&List={listGuid}&query=Title%20Status&XMLDATA=TRUE&FilterField1=Status&FilterValue1=In%20Progress
For a full list of what can be done with this technique, check out the URL Protocol or the older Using the URL Protocol on MSDN.
Free MOSS/WSS 2007 Web Part - Hide Controls via JavaScript
Note: version 0.2 posted with minor bugfix 15th March 08!
This is my small contribution to the SharePoint world. It is a web part that once added to a web part page, allows you to customise the display by adding JavaScript to selectively hide controls on the page . Ever needed to hide a field from display/edit for a certain audience? Well here is a way do it without requiring SharePoint Designer and having to break a page from it’s site definition (unghosting).
Before and after shots below (look ma - no top button!)
To fully understand what is being done here, I suggest you read my series of articles on the use of JavaScript in SharePoint. Part 3 in particular will show you how to safely add this web part to pages with editing disabled (NewForm.aspx, EditForm.aspx and DispForm.aspx)
The full series can be found here: Part 1, Part 2, Part 3, Part 4, Part 5 and Part 6.
Kudos to Jeremy Thake for feedback and some code contribution. Despite being seriously metrosexual, he is otherwise otherwise very cool :-P.
Now two important warnings:
Warning 1: This is an alpha quality release and I may never touch it again So you very likely *will* break it. If there is enough interest, I am happy to pop it on codeplex
Warning 2: This web part should NOT be considered as a security measure and thus used in any security sensitive scenario (such as an extranet or WCM site). JavaScript by its very nature can be trivially interfered with and thus other methods (server side) should be employed in these scenarios to prevent interference at the browser.
You can download by reading the disclaimer and clicking the button below..
THIS CODE IS PROVIDED UNDER THIS LICENSE ON AN “AS IS” BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER
Use at your own risk!
To install perform the following commands
stsadm.exe” -o addsolution -filename CleverWorkAroundsHideFields.wsp
stsadm.exe” -o execadmsvcjobs
stsadm.exe” -o deploysolution -name CleverWorkAroundsHideFields.wsp -immediate -allowgacdeployment -allcontenturls
stsadm.exe” -o execadmsvcjobs
To remove/reinstall perform the following commands
stsadm.exe” -o retractsolution -name CleverWorkAroundsHideFields.wsp -immediate -allcontenturls
stsadm.exe” -o execadmsvcjobs
stsadm.exe” -o deletesolution -name CleverWorkAroundsHideFields.wsp
stsadm.exe” -o execadmsvcjobs
stsadm.exe” -o addsolution -filename CleverWorkAroundsHideFields.wsp
stsadm.exe” -o execadmsvcjobs
stsadm.exe” -o deploysolution -name CleverWorkAroundsHideFields.wsp -immediate -allowgacdeployment -allcontenturls
stsadm.exe” -o execadmsvcjobs
12 Mart 2008 Çarşamba
Adding web parts programmatically in SharePoint
The code to accomplish this is quite easy, basically there are two scenarios: you add a web part that is displaying data for a list, or you add any other web part (e.g. a custom web part or a 3rd party web part like the SmartPart). The code for the first scenario is:
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
// Get a reference to a web and a list
SPSite site = new SPSite("http://localhost:8000");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["Contacts"];
// Instantiate the web part
ListViewWebPart wp = new ListViewWebPart();
wp.ZoneID = "Left";
wp.ListName = list.ID.ToString("B").ToUpper();
wp.ViewGuid = list.DefaultView.ID.ToString("B").ToUpper();
// Get the web part collection
SPWebPartCollection coll =
web.GetWebPartCollection("default.aspx",
Storage.Shared);
// Add the web part
coll.Add(wp);
First you get a reference to the SPWeb in which you want to add the web part, and to the list you want to use (in this example the Contacts list). Next you create an instance of the ListViewWebPart class, in which you can set the ZoneID, the ListName and the ViewGuid. This is the tricky part, the ListName property should contain the ID of your list (a GUID), not the name of your list!! But the ListName property is of the type string, so you need to convert the List GUID to a string using .ToString(“B”).ToUpper(). The same goes for the ViewGuid. Finally you need to get a reference to the WebPartCollection for the page in which you want to add the web part (in this example the home page, being default.aspx). Now you can add the web part using the Add method.
For the second scenario, the code is as follows:
// Get a reference to a web and a listThe first section is the same, get a reference to your site and the WebPartCollection (you don’t need a reference to a list). Next you need to build a XML string containing the information about the web part you want to add. The contents of that string are the same as the DWP file that you need to create to use your custom web parts. A trick to figure out what needs to be in there (especially if you want to specify values for some properties) is to put the web part on a page (using the web interface), and choose “Export” from the dropdown menu of the web part. This will save the contents of the DWP in a file. Finally you can add the web part by calling the Add method of the WebPartCollection and using the dwp string as a parameter.
SPSite site = new SPSite("http://localhost:8000");
SPWeb web = site.OpenWeb();
// Get the web part collection
SPWebPartCollection coll =
web.GetWebPartCollection("default.aspx",
Storage.Shared);
string dwp = @"
http://www.w3.org/2001/XMLSchema" ";
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns=""http://schemas.microsoft.com/WebPart/v2"">
SmartPart List 1.0.0.0 Left
SmartPart, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=dd064a5b12b5277a
SmartPart.UserControlWebpart
~\UserControls
coll.Add(dwp);
I have recently had to come up with a way to programmatically add a Web Part to a large number of existing publishing pages. It took me a little while to find the exact way to do it, so I thought I would post the source code here.
Attached is the C# code that will iterate over a bunch of pages in a bunch of sites, and then add a doclib Web Part on all those pages, in a specific Web Part Zone. The meat of the code is this:
SPSite mySiteCollection = new SPSite("http://sharepoint");
SPWeb w = mySiteCollection.AllWebs["/whatever"];
SPFile f = w.GetFile("Pages/Page.aspx");
SPLimitedWebPartManager wpm = f.GetLimitedWebPartManager(PersonalizationScope.Shared);
SPList l = w.Lists["Documents"];
ListViewWebPart wp = new ListViewWebPart();
wp.ListName = l.ID.ToString("B").ToUpper();
wp.ViewGuid = l.DefaultView.ID.ToString("B").ToUpper();
wpm.AddWebPart(wp, "Zone 1", 1);
f.Publish("Added Web Part");
f.Approve("Web Part addition approved");
This bit of code uses an SPLimitedWebPartManager to add the ListViewWebPart to the "Zone 1" Web Part Zone. The page is then published and approved.
Kaynak:
http://blogs.msdn.com/tconte/archive/2007/01/18/programmatically-adding-web-parts-to-a-page.aspx