Monday, February 7, 2011

Hiding the Name.dll ActiveX Control

If you are working on a public-facing Internet site, you should be aware that SharePoint may show a particularly annoying message at the top of Internet Explorer like shown below (This website wants to run the following add-on: ‘Name ActiveX Control’ from ‘Microsoft Corporation’: If you trust the website and the add-on and want to allow it to run, click here…)

NameDll

The message asks the user to run the Name.dll ActiveX Control add-on because the users don’t the SharePoint Server added to their trusted sites list. This control enables presence information to be displayed for authenticated users in SharePoint, and typically shows their availability in external Instant Messaging programs from inside SharePoint. Since anonymous users don’t really need this functionality you can turn off this message by using one of the following method:

  • In SharePoint 2010 the message can be turned off from Central Administration –> Manage Web Applications –> General Settings. Simply set Enable the Person Names Smart Tag and Online Status for Members to No. This will turn off the presence information and remove the ActiveX message for the entire web application.
  • Alternatively you can you can disable the message and functionality from a custom master page. Simply add the following code to your master page:

<script type=”text/javascript”>
    function ProcessImn(){}
    function ProcessImnMarkers(){}
</script>

This JavaScript code overrides the functions in SharePoint that cause this ActiveX message.

Sunday, February 6, 2011

SharePoint Guidance 2010 Hands On Lab Has Been Released

SharePoint Guidance 2010 Hands On Lab has just been released to CodePlex: http://spg.codeplex.com/ 

It consist of six labs:

  • Add and Remove Application Setting in Feature Receiver and Retrieve them in Web Part
  • Add and Remove Application Setting in Console Application and Use Hierarchy of them in Web Part
  • Add, Update, Remove, Search Application Setting in Sandbox
  • Read Application Setting in Sand Box Solution with ConfigProxy
  • Register SharePoint Logger in Feature Receiver and Use Logger in Web Part
  • Register Service in Feature Receiver and Display Service Instance in Web Part

Thursday, February 3, 2011

Random Number Generation - Not Random At All

using System;

namespace MyRandom
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                // Generate random number
                Random random = new Random();
                int myNum = random.Next(0, 10);
                // Write generated random number to console window
                Console.WriteLine("My random number: " + myNum.ToString());
            }
            // Pause running console window
            Console.ReadLine();
        }
    }
}

Did you know that if you declared Random Class within the loop as shown in the code sample above, it will not generate random number at all – in fact it will generate same number as shown in the screenshot below:

RandomNumber

To fix this problem, you need to declare Random Class outside of for loop as follows:

using System;

namespace MyRandom
{
    class Program
    {
        static void Main(string[] args)
        {
            Random random = new Random();
            for (int i = 0; i < 10; i++)
            {
                // Generate random number
                int myNum = random.Next(0, 10);
                // Write generated random number to console window
                Console.WriteLine("My random number: " + myNum.ToString());
            }
            // Pause running console window
            Console.ReadLine();
        }
    }
}

Windows Phone Training Kit Update Released

The Windows Phone Training Kit has been released today which includes few new labs – you can download Windows Phone 7 Training Kit for Developers here: RTM Refresh. The online training kit was also updated.

For more information, see: http://windowsteamblog.com/windows_phone/b/wpdev/archive/2011/02/02/windows-phone-training-kit-update.aspx

Using CrmDiscoveryService Web Service To Find Sales Org and Web Service End Point

Microsoft Dynamics CRM CrmDiscoveryService Web service provides a list of Web service endpoint URLs for each sales organization that you are a member of. The following sample code shows you how to use the Web service:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using CRMDiscoveryServices;
using System.Configuration;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            // Get CRM Dynamics credential from web configuration
            string crmUserId = ConfigurationManager.AppSettings["CRMUSERID"];
            string crmPassword = ConfigurationManager.AppSettings["CRMPASSWORD"];
            string crmDomain = ConfigurationManager.AppSettings["CRMDOMAIN"];

            // Create and configure the CrmDiscoveryService Web service proxy.
            CrmDiscoveryService discoveryService = new CrmDiscoveryService();
            discoveryService.Credentials = new System.Net.NetworkCredential(crmUserId, crmPassword, crmDomain);

            // Retrieve the list of organizations that the logged on user belongs to.
            RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
            RetrieveOrganizationsResponse orgResponse = (RetrieveOrganizationsResponse)discoveryService.Execute(orgRequest);

            // Locate the target organization in the list.
            if (orgResponse != null && orgResponse.OrganizationDetails.Length > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (OrganizationDetail orgDetail in orgResponse.OrganizationDetails)
                {
                    sb.AppendLine("<B>Organisation name:</B> " + orgDetail.OrganizationName
                        + " <B>CRM Web application.:</B> " + orgDetail.WebApplicationUrl
                        + " <B>CrmService Web service URL:</B> " + orgDetail.CrmServiceUrl + "<BR/>");
                }
                Response.Write(sb.ToString());
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

Please note that you need to add the CrmDiscoveryService web reference to your project. To add the web reference, select Add Service Reference, click Advanced, and then click Add Web Reference. In the URL field, paste the following string, replacing <server name> and <port number>:

http://<servername>:<port>/mscrmservices/2007/ad/crmdiscoveryservice.asmx?WSDL

Turn Off Warning Message On Unsupported Browsers in SharePoint 2010

Browser support in SharePoint 2010 has been greatly improved over SharePoint 2007, check out Technet’s Browser Support Matrix for SharePoint 2010. However Internet Explorer 6 (IE6) and other commonly used browsers are not browsers SharePoint 2010 supports from a content-authoring perspective. When you open a SharePoint page using IE6 browser, the following simple message will be displayed in the message box:

“Your Web browser will have problems displaying this web page. Changes to the sites may not function properly. For a better experience please update your browser to its latest version.”

WarningLegacyBrowser

Let say you are able to create a specific master page that works for anonymous IE6 users but how to turn off the warning message for all users with legacy unsupported browsers like IE6?

It’s simple! Find the following line at the bottom of the out-of-the-box master pages:

<SharePoint:WarnOnUnsupportedBrowsers runat=”server”/>

If you want to turn off the warning message for all users, you can simply remove it from master pages.

What Developers Must Know About HTML5 and IE9

Interesting article from MSDN: Internet Explorer 9 Beta Guide for Developers.

Wednesday, February 2, 2011

How To Turn Off Master Pages Applying to Application Pages

You may not want your custom branding to apply to the application pages, normally the way I do this is by not applying custom master page to SharePoint 2010 as the System Master Page. But wait, although this method prevents the application pages from showing the custom branding, but it also prevents the branding from showing on any nonpublising page too :(

I found a better way to do this that is by stop master pages from applying to application pages by turning off the feature completely from Central Administration, as follows:

  • Open Central Administration on the SharePoint server.
  • Under Application Management, click Manage web applications.
  • Select the desired web application from the list, and then from the ribbon, click General Settings.
  • In the dialog that appears, scroll down to Master Page Setting for Application _Layouts Pages and select No.
  • Scroll to the bottom of the dialog and click OK.

MasterPageSettingsForLayoutPage

    Now custom master pages for this entire web application will not apply to the application pages.

    Tuesday, February 1, 2011

    Delete a Corrupted List Using STSADM

    If you have a list that might appear to be in a corrupted state, when you try to delete it using SharePoint Web UI you will get the following error message:

    Invalid file name.
    The file name you specified could not be used.  It may be the name of an existing file or directory, or you may not have permission to access the file.<nativehr>0x81020030</nativehr><nativestack></nativestack>

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.Runtime.InteropServices.COMException: Invalid file name.
    The file name you specified could not be used.  It may be the name of an existing file or directory, or you may not have permission to access the file.<nativehr>0x81020030</nativehr><nativestack></nativestack>

    Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

    By using STSADM operation’s forcedeletelist, you can delete the corrupted list, here is the syntax:

    stsadm -o forcedeletelist -url <URL>

    Example:

    stsadm –o forcedeletelist –url http://sharepointserver/lists/yourcorruptedlist

    The Disposable in SharePoint Development

    If you don’t properly dispose of objects in the SharePoint object model that implement IDisposable, you will have memory usage problems in your application. The objects to be most careful of are SPSite and SPWeb, which must be disposed of because they consume large amounts of unmanaged memory.

    But Wait… I Thought Garbage Collection Took Care of Memory Management?

    The answer to this question is that an object like SPSite uses a mix of managed and unmanaged code. The memory usage of the managed side of SPSite is monitored by the .NET garbage collector, and when enough memory is used by the managed code, the garbage collector will kick in. The problem is that the .NET garbage collector doesn’t watch the unmanaged code’s use of memory and the unmanaged memory use is much greater than the managed memory use. So you can quickly run out of memory on the unmanaged
    side without .NET ever feeling like it needs to do a garbage collection.

    There are several coding patterns that I use when working with SPWeb and SPSite and other objects that implement IDisposable, so I would like to share with all of you:

    Using Dispose with SPSite or SPWeb  object

    SPSite oSite = new SPSite("http://localhost");

    // Do something

    SPWeb oWeb = oSite.OpenWeb();

    // Do something

    oWeb.Dispose();
    oSite.Dispose();

    The using clause with SPSite or SPWeb

    using (SPSite oSite = new SPSite("http://localhost"))
    {
        // Do something
        using (SPWeb oWeb = oSite.OpenWeb())
        {
            // Do something
        }
    }

    Using Dispose in the finally block of try, catch, finally code

    SPSite oSite = null;
    SPWeb oWeb = null;
    try
    {
        if ((oSite = new SPSite("http://localhost")) != null)
        {
            oWeb = oSite.OpenWeb();
            // Do something
        }
    }
    catch (Exception ex)
    {
        // Handle exception
    }
    finally
    {
        if (oWeb != null)
            oWeb.Dispose();

        if (oSite != null)
            oSite.Dispose();
    }

    Using Dispose with an object in a foreach loop

    using (SPSite oSite = new SPSite("http://localhost"))
    {
        foreach (SPWeb oWeb in oSite.AllWebs)
        {
            try
            {
                // Do something here
            }
            catch (Exception ex)
            {
                // Handle exception
            }
            finally
            {
                if (oWeb != null)
                    oWeb.Dispose();
            }
        }
    }

    Do Not Dispose of the SPSite and SPWeb Return By SPContext

    According to SharePoint best practices, SPSite and SPWeb objects returned by SPContext.Site, SPContext.Current.Site, SPContext
    .Web, and SPContext.Current.Web should not be explicitly disposed by user code.

    SharePoint Dispose Checker Tool

    Alternatively, you can use SPDisposeCheck to measure your code against known Microsoft dispose best practices.

    Saturday, January 29, 2011

    Malaysia SharePoint User Group (MySpug), Where Are You?

    Today, I realise that MySpug (http://spugmalaysia.org) web site no longer exist – rather a sad news to all SharePoint end-users, IT pros and developers in Malaysia.

    spugdead

    MySpug was launched in mid 2009 and surprisingly I knew nothing about their existence until today! That’s sound weird, eh? considering that I’ve been working around SharePoint since version 2001. My friend said they had organised quite a number of activities and talks in Malaysia (but I didn’t get any invitation *sigh* – why?? communication break down?? publicity??). I am not sure whether MySpug is still active though – I will have to find out.

    Come on and Matthew Khaw and Patrick Yong!

    Site Settings Display A Blank Page

    When you use standard hostname given to the address of the loopback network interface, “localhost”, as URL to access the SharePoint Site Settings page of any sub sites for example: http://localhost/subsite1/_layouts/settings.aspx, a blank page will be displayed and the following entries will be logged in the SharePoint ULS:

    • 01/29/2011 18:43:04.10 | w3wp.exe | (0x1CB4) | 0x1DDC | SharePoint Foundation | Logging Correlation Data | Name=Request (GET:http://<<SERVERNAME>>:80/<<SUBSITE>>/_layouts/settings.aspx)
    • 01/29/2011 18:43:04.11 | w3wp.exe | (0x1CB4) | 0x1DDC | SharePoint Foundation | Monitoring | Leaving Monitored Scope (Request (GET:http://<<SERVERNAME>>:80/<<SUBSITE>>/_layouts/settings.aspx)). Execution Time=1.96949915988322
    • 01/29/2011 18:43:04.11 | w3wp.exe | (0x1CB4) | 0x1F24 | SharePoint Foundation | Configuration | Alternate access mappings have not been configured.  Users or services are accessing the site http://<<SERVERNAME>> with the URL http://localhost.  This may cause incorrect links to be stored or returned to users.  If this is expected, add the URL http://localhost as an AAM response URL.  For more information, see: http://go.microsoft.com/fwlink/?LinkId=114854"/>    

    To fix this issue, all you need to do is to configure Alternate Access Mappings (AAM) by adding internal URLs “http://localhost” to the default zone as shown in screenshot below:

    AAM

    Friday, January 28, 2011

    Command To Start and Stop Windows Services For SharePoint

    If you like me who prefer Windows 7 x64 as your SharePoint 2010 development environment, most probably the following batch files would be useful to start and stop Windows Services for SharePoint when required:

    Start Windows Services For SharePoint

    REM Start SharePoint 2010 Services : http://sharepointmalaya.blogspot.com

    Echo Starting Services Required To Run SharePoint 2010

    NET START MSSQL$SHAREPOINT
    NET START IISADMIN
    NET START W3SVC
    NET START SPAdminV4
    NET START SPTimerV4
    NET START SPTraceV4
    NET START SPUserCodeV4
    NET START SPWriterV4
    NET START OSearch14

    pause

    Stop Windows Services For SharePoint

    REM Stop SharePoint 2010 Services : http://sharepointmalaya.blogspot.com

    Echo Stoping Services Required To Run SharePoint 2010

    NET STOP OSearch14
    NET STOP SPWriterV4
    NET STOP SPUserCodeV4
    NET STOP SPTraceV4
    NET STOP SPTimerV4
    NET STOP SPAdminV4
    NET STOP W3SVC
    NET STOP IISADMIN
    NET STOP MSSQL$SHAREPOINT

    pause

    Thursday, January 20, 2011

    View SharePoint Content and Settings From Visual Studio 2010

    One of coolest and newest features of Visual Studio 2010 is the ability to view SharePoint Content and Settings from Server Explorer.

    ServerExplorer

    To do this you are require to launch Visual Studio as an administrator. Locate the “Microsoft Visual Studio 2010” shortcut in the Start menu under All Programs > Microsoft Visual Studio 2010. Right click on the Microsoft Visual Studio 2010 shortcut and choose “Run as administrator” from the context menu.

    Alternatively, if you just want to make Visual Studio start up with administrator privileges every time you launch it, you can change the
    Microsoft Visual Studio 2010 shortcut properties to always run as administrator. To do this, right click on the Microsoft Visual Studio 2010 shortcut and choose Properties. Click the Compatibility tab and then check the “Run this program as an administrator” check box and
    press OK.

    VisualStudioSettings

    Wednesday, January 19, 2011

    How to Ensure a Full Farm Recovery

    SharePoint 2010 stores more configuration information in the content databases than SharePoint 2007, but you still need to be concerned with the following non-SharePoint components to ensure a successful farm recovery:

    SharePoint Root

    The \Program Files\Common Files\Microsoft Shared\Web server Extensions\14 folder often holds any customizations that your developers have made to your SharePoint implementation. These can include custom graphics, style sheets, and site definitions, to name a few possible modifications. It is important to back up the SharePoint Root on at least one of your Web front-end servers to ensure that these customizations can be recovered. Because the SharePoint Root should be identical on all Web front-end servers, it is not necessary to back up each one separately – makes a lot more easier.

    Inetpub folder

    This is another location that can be used to store customizations such as graphics and custom Web Parts. You also want to ensure that you have a copy of the Web.config file, because this contains any safe control entries required by custom or third-party Web Parts. Each Web application has a corresponding Inetpub folder on your Web front-end servers, so back up all!

    System Binaries

    In the event of server failure, you need to recover it to the state it was in before the failure. This can be done either by reinstalling all the system files, patches, service packs, and upgrades that were installed on the server, or by restoring your system files from backup. Often, backup utilities offer a disaster recovery option designed to recover your system to the exact state before the failure.

    IIS Settings

    SharePoint relies on Web sites hosted by Microsoft Internet Information Server (IIS) to provide access to SharePoint information. It is therefore important that you have a backup of the IIS configurations for the SharePoint servers in the farm. You can do this by opening the IIS Management console from Administrative Tools on the Start menu, right-clicking the server object, selecting All Tasks >  Backup/Restore Configuration option.

    To back up the IIS configuration information, use the AppCmd.exe command found in %WinDir%\System32\Inetsrv as shown here.

    appcmd.exe add backup "Your Backup Name"

    To restore that backup, run the command shown here.

    appcmd.exe restore backup "Your Backup Name"

    SSL Certificates

    You should always keep a backup of your SSL certificates, including the private key. Although this can be retrieved from a system state operating system backup, you must restore the entire system state to access the certificate store that was backed up using Certificate Manager. A configuration backup should always include the use of a password so that the restore is portable and not restricted to the original Web server.

    System State Data

    System state data includes the following items, which can be backed up by most disaster-recovery software as part of a normal system backup.

    • Start-up files
    • Registry
    • COM+ class registration database
    • IIS configuration
    • Active Directory
    • SYSVOL folder
    • DNS
    • Certificate store

    DNS Records

    If your DNS server is hosted on a domain controller, the system state data will include the DNS information. If DNS is hosted on a member server or stand-alone server, however, you must back up the Zonename.dns file located at C:\Windows\System32\DNS.