Microsoft Technology, .Net, BizTalk, Sharepoint & etc.

Liedong(Ken) Zheng, Senior SharePoint Developer at SIMPLOT

Archive for September, 2008

How To Debug WebPart in VS 2008

Posted by ken zheng on September 26, 2008

In some situations, it will be necessary to debug a web part. In order to make a WSS web part able to be debugged, the web.config of the WSS web site where you deploy your webpart to must be modified.

Open the Web.config file and modify the existing options to look like the following:

<customErrors mode=“Off” />

<compilation batch=”false” debug=”true“>

Once the web.config is modified, you can directly set breakpoint and hit F5 in a Visual Studio environment.

Posted in Sharepoint, VS2008 | Tagged: , | 1 Comment »

Create A WebPart in VS 2008

Posted by ken zheng on September 26, 2008

One of the tricky bits with developing WebParts using Visual Studio 2005 is the deployment aspects.

As mentioned in this article, you firstly have to create a strong-name key, and compile the DLL, load the assembly into the GAC, and include as a SafeControl.

There are STSADM scripts that can be used to do the same thing or you need to load your dll into Web Part Gallery

With the release of Visual Studio 2008, you can use SmartTemplate and WSPBuilder (Both available in CodePlex).

It registers the DLL in the GAC, adds the feature (installfeature) and activates the feature (WSP) for each chosen Web Application.

When the wizard completes, just have to flip back to SharePoint to turn it on for each particular Site Collection :

* Site Settings > Site Collection features > Activate

The WebPart will then be available from the WebPart gallery, and can be added to a page.

This is a great time-saver – making deployment of WebParts much easier.

You also can use Deploy function to deploy the dll for quick test.

There is a good example to show you how to do it. http://www.aspfree.com/c/a/Windows-Scripting/Beginning-SharePoint-Web-Part-Development/1/

But the problem is if you redeploy you may get error:
“This solution contains two assemblies with the same name, or the SharePoint server already has an assembly with the specified name.” when deploying a solution using the Visual Studio Extensions for SharePoint (VSEWSS) after you have already deployed it to a different site on the same server.

Answer:

Remove the solution’s assembly from the Global Assembly Cache (GAC).

· Gacutil /uf assemblyName (note: no .dll extension is specified)

· Rename or Remove the feature from “Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\FeatureName” (note: FeatureName may not be the same as assembly name – look in your manifest.xml to find the correct name)

If you deleted projects after you deploy the solution. You will get error as the manifest file still there.
Go to folder called pkg under your solution file folder and delete the folder which you have removed from solution

Posted in Sharepoint, VS2008 | Tagged: , | Leave a Comment »

Create A Site/Web Using Template in STSADM

Posted by ken zheng on September 26, 2008

1. First create a site collection based on what ever template that you would like to start with for example the Collaboration / Team Site template. Customise the template to what you would like. For example create additional document libraries and set versioning.
2. From the site settings, Look and Feel , Save site as template. Give it a file name, template name and description. Optionally choose if you would like any content that you have added to the template to be included.
3. Once this is done it will create the template.stp in the site template gallery. Browse to this gallery and download the file. Once you have this file copy it to your sharepoint server. Also if you are going to re-use the template you might want to delete the template from the gallery and then delete it from both recycle bins in the site collection recycle bin.
4. To add the template to central administration site templates you will need to use stsadm. I recommend that you add the path to the bin directory containing stsadm.exe to the system environment variables.

C:\source\site-templates>stsadm -o addtemplate -filename “project-simple.stp” -title “Project site – simple” -description “Project site template with a simple structure”

Operation completed successfully.

IIS must be restarted before this change will take effect. To restart IIS, opena command prompt window and type iisreset.

Deleting a template from the command line. Below is a code snipet of how to list the templates installed and then how to delete the template based on its title.

C:\source\site-templates>stsadm -o enumtemplates

IT Project Site – Language: 1033 – Site Template: _GLOBAL_#0 – Template Id: 1

C:\source\site-templates>stsadm -o deletetemplate -title “IT Project Site”

Operation completed successfully.

IIS must be restarted before this change will take effect. To restart IIS, open
a command prompt window and type iisreset.

C:\source\site-templates>

Posted in Sharepoint | Tagged: , | Leave a Comment »

Easiest Way To Create A Custom ASPX Page for SharePoint

Posted by ken zheng on September 24, 2008

First, create a Class Library project in vs 2005/2008.
Add Microsoft.SharePoint dll reference

Create a file called HelloWorld.aspx

<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>
<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master"
         Inherits="Microsoft.SharePoint.WebControls.LayoutsPageBase"  %>

<%@ Import Namespace="Microsoft.SharePoint" %>

<script runat="server">
  protected override void OnLoad(EventArgs e) {
    //SPWeb site = SPContext.Current.Web;
    SPWeb site = this.Web;
    lblSiteTitle.Text = site.Title;
    lblSiteID.Text = site.ID.ToString().ToUpper();
  }
</script>

<asp:Content ID="Main" contentplaceholderid="PlaceHolderMain" runat="server">
  <table border="1" cellpadding="4" cellspacing="0" style="font-size:12">
    <tr>
      <td>Site Title:</td>
      <td><asp:Label ID="lblSiteTitle" runat="server" /></td>
    </tr>
    <tr>
      <td>Site ID:</td>
      <td><asp:Label ID="lblSiteID" runat="server" /></td>
    </tr>
  </table>
</asp:Content>

<asp:Content ID="PageTitle" contentplaceholderid="PlaceHolderPageTitle" runat="server">
	Hello World
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" runat="server"
             contentplaceholderid="PlaceHolderPageTitleInTitleArea" >
	The Quintessential 'Hello World' of Application Page
</asp:Content>

or you can create a sepeate cs file but add code into you

  • Sign a strong key and build the project.
  • Add the assembly into GAC
  • Then Copy the HelloWorld.aspx to C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\Test
  • so now if you go to your site and add/_layouts/Test/HelloWorld.aspx, it should show the page

    Posted in Sharepoint | Tagged: | 2 Comments »

    EventHandler fo SharePoint

    Posted by ken zheng on September 24, 2008

    Make sure event handlers are enabled on the site where your survey is.

    1. To enable event handlers for your site, go to “SharePoint Central Administration”.
    2. Select “Application Management” tab and then select “Web application settings” in “SharePoint Web Application Management” section.
    3. Select your web application from the drop down. Click “Change Web Application” and then select your web application from the form that opens.
    4. Scroll down and locate the “Event Handlers” section and turn them on.
    5. Now go back to your site. You are ready to write an event handler

    6. Start a new “Class library” project in VS and select C# as the programming language. Project will contain just a few lines of code.

    Add Microsoft.SharePoint reference from C:\Program Files\Common Files\Microsoft Shared\web server
    extensions\12\ISAPI

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

    namespace VfmcSharepoint
    {
    public class UniqueID : SPItemEventReceiver
    {
    private static int GetUniqueId(SPWeb web)
    {
    int returnValue = -1;
    int retryCounter = 0;
    int uniqueId = -1;

    ReTry:
    try
    {
    // Get the list and list item
    SPList list = web.Lists["IPD Form"];

    // Set the value to return
    returnValue = list.ItemCount + 1;
    }
    catch (Exception ex)
    {
    // Handle the exception by retrying 5 times
    retryCounter += 1;
    if (retryCounter “Processes” and select the “w3wp.exe” process (may be more than one – select them all) and hit ok. when asked, select the “managedd code” option only (not script and sql)

    Posted in Sharepoint | Tagged: | Leave a Comment »

    Compact Your VPC

    Posted by ken zheng on September 22, 2008

    Here is the procedure to compact your VPC file, I had one VPC whose orignial size is 37 GB but after compact it goes down to 27 GB.

    1. Start the VPC
    2. Click “CD” and “select Capture ISO image”
    3. there is an iso under C:\Program Files\Microsoft Virtual PC\Virtual Machine Additions\Virtual Disk Precompactor
    4. run the compaction prep
    5. Shut down the VPC after Prep completed
    6. Go to the settings, select the hard drive and run the hard disk wizard, in that wizard you can choose the compact

    Posted in Uncategorized | Tagged: | Leave a Comment »

    XML AND DATASET

    Posted by ken zheng on September 19, 2008

    Very often you will need to parse xml files to get information so why not use dataset to have a oo view.
    If you have a xml file, you can use XML tool like XMLSpy to generate a schema .xsd file or write a simple code

    Dim MyDS As DataSet = New DataSet()
    MyDS.ReadXml(“test.xml”)

    MyDS.WriteXmlSchema(“C:\Temp\test.xds”)

    then in visual studio command line use xsd to generate class
    xsd.exe -c -l:vb -n:XmlSerializationOXI temp.xsd

    add both schema and class file to your project. Now you can load XML to your Dataset

    Dim ds As New DataSet()
    ‘ Load the schema into the DataSet
    ds.ReadXmlSchema(“temp.xsd”)

    ‘ Load the data into the data document
    Dim XDocStudents As New XmlDataDocument(ds)
    XDocStudents.Load(“C:\Temp\temp.xml”)

    Console.WriteLine(ds.Tables(0).Rows.Count)

    Posted in .Net | Tagged: , | Leave a Comment »

    Calling UserControl’s Event in ASP .NET Page By AJAX

    Posted by ken zheng on September 19, 2008

    If you have a usercontrol which has a button click event and you want to raise a postback like the button is clicked.

    User Control code to declare a global variable in javdsciprt for Postback

        Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
            MyBase.OnLoad(e)
    
            Dim sm As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            ScriptManager.RegisterStartupScript(Me.Page, Me.GetType(), "ClientID", String.Format("var logoutClientId = '{0}$LogoutLink';", Me.ClientID.Replace("_", "$")), True)
    
        End Sub
    
        Public Sub LogoutLink_Click(ByVal sender As Object, ByVal e As EventArgs) Handles LogoutLink.Click
            Page.LogoutCurrentUser("Sucessfully logged out.")
        End Sub
    

    The below javascipt is to logout when a full postback raised.

    window.onunload = function(){ unloadPageAndError();}
    
    var loader = function(sender, args) {
        if(!args.get_isPartialLoad()){
            PageMethods.CheckLogin(function(result){
                if(result)
                {
                    unloadPageAndError();
                }
            },
            function(error)
            {
                unloadPageAndError();
            }
            );
        }
    }
    
    var unloadPageAndError = function()
    {
        <strong>__doPostBack(logoutClientId,'')</strong>
    }
    
    Sys.Application.add_load(loader);
    

    Below is a Web Method in your web page, you need to enable your scriptmanger.enablepagemethod = true

        <System.Web.Services.WebMethod()> _
        Public Shared Function CheckLogin() As Boolean
            Return UserContext() Is Nothing
        End Function
    

    Posted in .Net | Tagged: , | Leave a Comment »

    Register JavaScripts in 2 ways

    Posted by ken zheng on September 19, 2008

    You can register your JavaScript in server side by 2 ways

            ' The very first control added to the form must be the AJAX script manager.
    		Dim cl As ClientScriptManager = Me.ClientScript
    		Dim cstype As Type = Me.GetType()
    
    		cl.RegisterClientScriptInclude(cstype, "DefaultScript", ResolveClientUrl("~/JScript Files/Test.js"))
    
            myScriptManager = New ScriptManager
            myScriptManager.ID = "__PageScriptManager"
            myScriptManager.EnablePageMethods = True
    
            myScriptManager.RegisterStartupScript(Me, GetType(Page), "StartManualTearDownScript", "manualTearDown.init();", True)
    
            If Me.PageAccess = PageAccessType.SecurePage Then
                Dim ref As New System.Web.UI.ScriptReference("JScript Files/Secure.js")
                myScriptManager.Scripts.Add(ref)
            End If
    
            myScriptManager.AsyncPostBackTimeout = WebConfigurationHelper.AsyncPostBackTimeout
    
            myHtmlForm.Controls.Add(myScriptManager)
    

    Posted in .Net | Tagged: | Leave a Comment »

    EnablePageMethods

    Posted by ken zheng on September 19, 2008

    You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds. To call serverside code from javascript, you will need to use AJAX, and the easiest way out, is to use the ASP.NET AJAX Extensions.
    One option while using Microsoft ASP.NET AJAX is to call ASP.NET Web services (.asmx files) from the browser by using client script. The script can call a webservice containing server-based methods (Web methods) and invoke these methods without a postback and without refreshing the whole page. However this approach could be overkill sometimes, to perform the simplest of tasks. Moreover the logic needs to be kept in a separate .asmx file. We need something that is more ‘integrated’ with our solution.
    The option we are going to use in this article involves PageMethods. A PageMethod is basically a public static method that is exposed in the code-behind of an aspx page and is callable from the client script. PageMethods are annotated with the [WebMethod] attribute. The page methods are rendered as inline JavaScript.

    Troubleshooting: ‘PageMethods Is ‘Undefined’’ error

    1. Try setting EnablePageMethods=”true” in the script manager tag

    2. Don’t add the javascript references or code in the section. Add it to the tag.

    3. Page methods needs to be static in code behind.

    Code

    <%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>PageMethod</title>
        <script type="text/jscript">
        function GetUser(){
            var oUser={
                ID : "007",
                Name : "jeff"
            };
            return oUser;
        }
    
        function CallServer(){
            var oUser = GetUser();
            PageMethods.GetServerUser(oUser, CallServerResult);
        }
    
        function CallServerResult(result){
            alert('Server:\n'+'ID:'+result.ID+'\nName:'+result.Name);
        }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
                </asp:ScriptManager>
                <input type="button" value="執行 PageMethod" onclick="CallServer()" />
    
                </div>
        </form>
    </body>
    </html>
    
        <System.Web.Services.WebMethod()> _
        Public Shared Function GetServerUser(ByVal Value As TUserData) As TUserData
            Value.ID = "012"
            Value.Name = "tony"
            Return Value
        End Function
    
    <Serializable()> _
    Public Class TUserData
        Dim FID As String = String.Empty
        Dim FName As String = String.Empty
    
        Public Property ID() As String
            Get
                Return FID
            End Get
            Set(ByVal value As String)
                FID = value
            End Set
        End Property
    
        Public Property Name() As String
            Get
                Return FName
            End Get
            Set(ByVal value As String)
                FName = value
            End Set
        End Property
    End Class
    

    A good article is here

    http://www.dotnetcurry.com/ShowArticle.aspx?ID=109&AspxAutoDetectCookieSupport=1

    Posted in .Net | Tagged: | Leave a Comment »