Tuesday, July 12, 2011

Undo "Add To Reject List" in Samsung Mobile

Navigate to following menu options to Add/Edit/Delete any number from reject list:

Settings > Application settings > Call > All calls > Auto reject > Reject list

Here you can find the Reject list.
You can Add/Edit/Delete number which you want to maintain in Reject List.

Reference: Samsung Forum

Monday, July 11, 2011

Creating Custom Field in SharePoint 2010

In this post basically I tried to answer following questions:
A. What is Custom Field in SharePoint?
B. What are the steps to implement Custom Field in SharePoint?
C. How to override Save button while creating New Item in SharePoint's List?
D. How to consume Custom Field?


I explained the above questions with following scenario:
1. Created a column based on custom field.
2. Override the Save button of New Item page.
3. In Save button click, beside performing normal operation, I am setting the another column value with concated value of custom field column and current TimeStamp.


A. What is Custom Field in SharePoint?
=============================================
Exceprt from MSDN site-
Although site columns provide users and developers with new capabilities in reuse, you can define a reusable column definition that is even more powerful. With Microsoft SharePoint Foundation 2010, you can drop down to a lower level by creating custom field types.
Reference: Creating Custom SharePoint 2010 Field Types


Exceprt from Chak's blog-
In SharePoint, a site column is a reusable column definition, or template, that you can assign to multiple lists across multiple SharePoint sites. Site columns are associated to a particular Data Type. This Data Type is called a Field. For example, when you create a site column, you are also prompted to select the type of information, which is nothing but a Data Type or a Field.

Sometimes, it is necessary for us to create our own custom field that does not conform to the field types included in SharePoint by default.

All you have to do is – create a custom field which would result in creating a Field Class, Field Control and Field Type Definitions.
1. The Field Class should inherit from any of the SPField classes.
2. The Field Control should have Field Rendering Control and a Field Rendering Template.
3. The Field Type Definitions is a XML file which contains some information about the custom field.


Reference: SharePoint: Creating a custom field




B. What are the steps to implement Custom Field in SharePoint?
=====================================================================

Following Components/Files are required for creating Custom Field:

1. Add Assembly reference of PresentationFramework
2. UserControl/ASCX in SharePoint Mapped CONTROLTEMPLATES folder of 14 hive
3. XML in SharePoint Mapped XML folder of 14 hive
4. XSL in SharePoint Mapped XSL folder of 14 hive [Optional]
5. C# class for CustomField
6. C# class for CustomFieldControl
7. C# class for CustomFieldValidationRule [Optional]



1. Steps to Add PresentationFramework reference:
=======================================================

Solution Explorer > Project > References > .Net tab > Select PresentationFramework


2. Steps to add UserControl:
==================================

a. Add CONTROLTEMPLATES Mapped Folder:

Solution Explorer > Project > Right-Click > Add > SharePoint Mapped Folder...

Select desired folder in opened pop-up window.


b. Add UserControl in Project:



UserControl File:

Installed Templated > Visual C# > SharePoint > 2010 > User Control [Middle Pane] > Enter desired name


Code snippet for User Control [e.g. AviCustomNameField.ascx]:

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, 
PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" 
Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, 
PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" 
Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, 
PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" 
Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, 
PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %> 
<%@ Register Tagprefix="WebPartPages" 
Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, 
Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" %>
<SharePoint:RenderingTemplate ID="AviCustomNameFieldControl" runat="server">
    <Template>
        <table>
            <tr>
                <td>
                    <asp:TextBox ID="MyCustomNameText" runat="server" 
                                    Width="385px" />
                </td>
            </tr>
        </table>
    </Template>
</SharePoint:RenderingTemplate>
<SharePoint:RenderingTemplate ID="AviCustomNameFieldControlForDisplay" 
                                 runat="server">
    <Template>
        <table>
            <tr>
                <td>
                    <asp:Label ID="MyCustomNameLabel" runat="server" 
                                  Width="385px" />
                </td>
            </tr>
        </table>
    </Template>
</SharePoint:RenderingTemplate>




3. Steps to add XML in SharePoint Mapped XML folder of 14 hive:
==================================================================
a. Add SharePoint Mapped Folder for XML [as mentioned in earlier steps]
b. Add new XML file [as mentioned in earlier steps]
c. Code snippet for XML [e.g. fldtypes_AviCustomNameField.xml]

<?xml version="1.0" encoding="utf-8" ?>
<FieldTypes>
  <FieldType>
    <Field Name="TypeName">AviCustomNameField</Field>
    <Field Name="ParentType">Text</Field>
    <Field Name="TypeDisplayName">Avi Custom Name Field</Field>
    <Field Name="TypeShortDescription">Avi Custom Name Field</Field>
    <Field Name="UserCreatable">TRUE</Field>
    <Field Name="ShowOnListCreate">TRUE</Field>
    <Field Name="ShowOnSurveyCreate">TRUE</Field>
    <Field Name="ShowOnDocumentLibraryCreate">TRUE</Field>
    <Field Name="ShowOnColumnTemplateCreate">TRUE</Field>
    <Field Name="FieldTypeClass">Avi.AviCustomNameField,$SharePoint.Project.AssemblyFullName$</Field>
  </FieldType>
</FieldTypes>


Note: Prefix the file name(s) for XML/XSL file as fldtypes_


4. Steps to add XSL in SharePoint Mapped XSL folder of 14 hive:
==================================================================
a. Add SharePoint Mapped Folder for XSL [as mentioned in earlier steps]
b. Add new XSL file [as mentioned in earlier steps]
c. Code snippet for XSL [e.g. fldtypes_AviCustomNameField.xsl]

<xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema"
                xmlns:d="http://schemas.microsoft.com/sharepoint/dsp"
                version="1.0"
                exclude-result-prefixes="xsl msxsl ddwrt"
                xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
                xmlns:asp="http://schemas.microsoft.com/ASPNET/20"
                xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:msxsl="urn:schemas-microsoft-com:xslt"
                xmlns:SharePoint="Microsoft.SharePoint.WebControls"
                xmlns:ddwrt2="urn:frontpage:internal">
  <xsl:template match="FieldRef[@Name = 'AviCustomNameField']" mode="Text_body">
    <xsl:param name="thisNode" select="." />
    <span style="background-color:lightgreen;font-weight:bold">
      <xsl:value-of select="$thisNode/@*[name()=current()/@Name]" />
    </span>
  </xsl:template >
</xsl:stylesheet>


Note: Prefix the file name(s) for XML/XSL file as fldtypes_


5. Steps to add C# class for CustomField:
================================================
a. Add new C# file as per following figure:


Installed Templated > Visual C# > Class [Middle Pane] > Enter desired name

b. Code snippet for CustomField [e.g. AviCustomNameField.cs]

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Security;
using System.Windows.Controls;
using System.Globalization;
using System.Security.Permissions;

namespace Avi
{
    class AviCustomNameField : SPFieldText
    {
        public AviCustomNameField(SPFieldCollection fields, string fieldName)
            : base(fields, fieldName)
        {
        }

        public AviCustomNameField(SPFieldCollection fields, string typeName, 
                                  string displayName)
            : base(fields, typeName, displayName)
        {
        }

        public override BaseFieldControl FieldRenderingControl
        {
            [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
            get
            {
                BaseFieldControl fieldControl = new AviCustomNameFieldControl();
                fieldControl.FieldName = this.InternalName;
                return fieldControl;
            }
        }

        public override string GetValidatedString(object value)
        {
            if ((this.Required == true) && ((value == null) 
               || ((String)value == "")))
            {
                throw new SPFieldValidationException(this.Title + 
                          " must have a value.");
            }
            else
            {
                AviCustomNameFieldValidationRule rule 
                   = new AviCustomNameFieldValidationRule();
                ValidationResult result 
                   = rule.Validate(value, CultureInfo.InvariantCulture);
                if (!result.IsValid)
                {
                    throw new
                          SPFieldValidationException((String)result.ErrorContent);
                }
                else
                {
                    return base.GetValidatedString(value);
                }
            }
        }
    }
}


6. Steps to add C# class for CustomFieldControl:
================================================
a. Add new C# file [as mentioned in earlier steps]
b. Code snippet for CustomFieldControl [e.g. AviCustomNameFieldControl.cs]

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.IO;
using System.Collections;

namespace Avi
{
    class AviCustomNameFieldControl : BaseFieldControl
    {
        protected TextBox MyCustomNameText;
        protected Label MyCustomNameLabel;

        protected override string DefaultTemplateName
        {
            get
            {
                if (this.ControlMode == SPControlMode.Display)
                {
                    return this.DisplayTemplateName;
                }
                else
                {
                    return "AviCustomNameFieldControl";
                }
            }
        }

        public override string DisplayTemplateName
        {
            get
            {
                return "AviCustomNameFieldControlForDisplay";
            }
            set
            {
                base.DisplayTemplateName = value;
            }
        }

        protected override void CreateChildControls()
        {

            base.CreateChildControls();

            this.MyCustomNameText = 
               (TextBox)TemplateContainer.FindControl("MyCustomNameText");
            this.MyCustomNameLabel =
               (Label)TemplateContainer.FindControl("MyCustomNameLabel");


            if (this.ControlMode != SPControlMode.Display)
            {
                if (!this.Page.IsPostBack)
                {
                    if (this.ControlMode == SPControlMode.New)
                    {

                    }
                }
            }
            else
            {
                if (this.MyCustomNameLabel != null)
                {
                    MyCustomNameLabel.Text = (String)this.ItemFieldValue;
                    //this.MyCustomNameLabel.Text =
                      SPContext.Current.ListItem["MyName"].ToString();
                }
            }
        }

        public override object Value
        {
            get
            {
                EnsureChildControls();
                return base.Value;
            }
            set
            {
                EnsureChildControls();
                base.Value = (String)value;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            // add save handler only in New and Edit modes
            if ((SPContext.Current.FormContext.FormMode == SPControlMode.New)
                || (SPContext.Current.FormContext.FormMode == SPControlMode.Edit))
            {
                SPContext.Current.FormContext.OnSaveHandler
                    += new EventHandler(MyCustomSaveHandler);
            }
        }

        protected void MyCustomSaveHandler(object sender, EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                SPContext.Current.ListItem["SampleNameWithTimeStamp"]
                    = MyCustomNameText.Text
                    + " - " + DateTime.Today.ToShortDateString();

                SPContext.Current.ListItem["MyName"] = MyCustomNameText.Text;
                
                SPContext.Current.ListItem.Update();
            }
            else
            {
                // do actions instead of save
            }
        }

    }
}



7. Steps to add C# class for CustomFieldValidationRule:
================================================
a. Add new C# file [as mentioned in earlier steps]
b. Code snippet for CustomFieldValidationRule[e.g. AviCustomNameFieldValidationRule.cs]

using System;
using System.Windows.Controls;
using System.Globalization;

namespace Avi
{
    public class AviCustomNameFieldValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, 
                                                  CultureInfo cultureInfo)
        {
            String CustomName = (String)value;
            bool result = isValidCustomName(CustomName);
            if (result != true)
            {
                return new ValidationResult(false, "Enter valid Name.");
            }
            else
            {
                return new ValidationResult(true, "Name Entered is correct.");
            }
        }
        public static bool isValidCustomName(string CustomName)
        {
            //Logic to validate data
            return true;
        }
    }
}




C. How to override Save button while creating New Item in SharePoint's List?
===================================================================================
a. Register custom method to Save button click in OnInit page event
Excerpt code snippet:
protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            // add save handler only in New and Edit modes
            if ((SPContext.Current.FormContext.FormMode == SPControlMode.New)
                || (SPContext.Current.FormContext.FormMode == SPControlMode.Edit))
            {
                SPContext.Current.FormContext.OnSaveHandler
                    += new EventHandler(MyCustomSaveHandler);
            }
        }

b. Implement custom method [e.g. MyCustomSaveHandler]
Excerpt code snippet:
protected void MyCustomSaveHandler(object sender, EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                // do actions in case of save
            }
            else
            {
                // do actions instead of save
            }
        }

Note: For complete code refer AviCustomNameFieldControl.cs class [mentioned earlier].



After adding all the mentioned files, this will be Final View of Solution/Project Explorer:



Miscellaneous:
Steps to change Assembly name and Default namespace:
===========================================================
Solution Explorer > Project > Right-Click > Properties > Change Assembly name and Default namespace as per requirement


D. How to consume Custom Field?
======================================
1. Create a Custom List

2. Create a new column and choose already created custom field [as per following figure]:

3. Following would be list structure without any data:

4. Add a new item to List:

5. List with data:


References:
==================
Creating a Custom Field Type for SharePoint 2010 (Email Validation Field)

How to override the default item save event using custom fields

Tuesday, June 28, 2011

Configure Microsoft Office Outlook 2010 Profile


* Open Microsoft Office Outlook Web Access

* Click User Control Panel

* Enter Credentials


* Go to – Downloads

* Download Your Outlook Profile

* Save it in Hard-disk [in my case I saved it in C drive with following name C:\filename.prf].



* Open Window's Run and run following command (Windows > Start > Run) :
outlook.exe /importprf C:\filename.prf

Reference :
customizing-outlook-profiles

Wednesday, March 23, 2011

JavaScript in Elements.xml file of a SharePoint Feature

Here my requirement was to create a menu/link in SharePoint's SiteActions, on click of which it redirects to custom site page created under Pages folder [/Pages/MyPage.aspx].

Challenges:
1. To execute JavaScript code on menu/link click.
2. Build the absolute URL of custom page.

Solution:
1. First create a SharePoint Feature to add a new menu/link in SiteActions.
2. Modify the Elements.xml using CustomAction/URLAction to execute the JavaScript code.
3. Write the required JavaScript code as per requirement [I have written a small piece of code to fetch the current server name and then build the absolute URL of custom page].
4. Install and Activate the SPFeature.



Following is the code snippet of Elements.xml file :

<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
                <CustomAction
                                GroupId = "SiteActions"
                                Location="Microsoft.SharePoint.StandardMenu"
                                Sequence="1000"
                                RequireSiteAdministrator="TRUE"
                                Title="My Links">
                                <UrlAction Url="javascript:function process()
                                { 
                                 var site='{SiteUrl}'; 
                                 var pageurl = ''; 
                                 var serverName = ''; 
                                 var endindex = site.indexOf('/', '10'); 
                                 if(endindex == -1) { serverName = site; } 
                                 else { serverName = site.substring(0, endindex); } 
                                 pageurl = serverName + '/Pages/MyPage.aspx'; 
                                 window.location = pageurl;         
                                }; 

                                process();"/>
                </CustomAction>
</Elements>

Friday, January 21, 2011

SharePoint 2010 Tips and Tricks

1. Change Site Icon/Logo of all pages in SharePoint 2010 (Wiki pages and Web part pages)

a. Wiki Pages:

Navigate to following path-
Site > Site Actions > Site Settings > Look and Feel > Title, description, and icon > URL

In URL textbox we can specify either Site Asset’s Image or 14 hive image.
Reference:
Change Wiki Page Site Logo

b. Web Part Pages:

  • Open Web Part page
  • Select Page ribbon Tab on top
  • Select Title Bar Properties
  • Scroll to the right and on the Web Part Page Title Bar properties
  • Specify either Site Asset’s Image or 14 hive image

Reference:
Change Web Part Page Site Logo



2. Enable Anonymous in SharePoint 2010


  1. Open SharePoint 2010 Central Administration
  2. Navigate to following path:
    Central Administration > Application Management > Manage web applications
  3. Select desired Web Application
  4. Click Authentication Providers icon in ribbon tab
  5. On the Authentication Providers pop-up window click on the Default zone.
  6. Under Edit Authentication, check Enable anonymous access and click Save.
  7. Go back to Web Application Management click on the Anonymous Policy icon in ribbon tab.
  8. Under Anonymous Access Restrictions select your Zone and set the Permissions to None – No policy and click Save.
  9. Now, open the desired web application in which we want to set anonymous access.
  10. Navigate to your top level site collection for the web application.
  11. Click the Site Actions > Site Settings > Users and Permissions > Site permissions.
  12. Under Permission Tools ribbon, click Anonymous Access icon
  13. Set the permissions to Entire Web site, or List and Libraries, or Nothing as per requirement
  14. Click OK.
  15. In case of Anonymous access at Web site level:
  • Navigate to Web Site > Site Actions > Site Permissions
  • Click Stop Inheriting Permissions icon in Permission Tools ribbon tab
  • After that we can see Anonymous Access icon in ribbon, click it
  • In Anonymous Access pop-up select desired check box as per requirement
  • Click Ok
        In case of Anonymous access at List and Library level:
  • Navigate to List or Library > List Tool tab > List tab > List Settings icon in ribbon > Permissions and Management > Permissions for this list
  • Click Stop Inheriting Permissions icon in Permission Tools ribbon tab
  • After that we can see Anonymous Access icon in ribbon, click it
  • In Anonymous Access pop-up select desired check box as per requirement
  • Click Ok

Reference:
Enable Anonymous Access 1
Enable Anonymous Access 1


3. Steps to use or consume SharePoint List or Libraries RSS functionality

  • If we are planning to use out-of-box RSS functionality of SharePoint’s List or Libraries using out-of-box RSS Viewer web part of SharePoint, then we have to enable Anonymous access at List or Library level.
  • If anonymous access is disabled at List or Library level then we will get following error:
    “The RSS webpart does not support authenticated feeds”

To solve the above error there are following options:

  • Set anonymous access at List or Library level
  • Use 3rd party RSS Feed Reader [available in Codeplex site]
  • Set IIS Authentication from NTLM to Kerberos
    [Central Administration > Application Management > Manage web applications > Select desired Web application > Select Authentication Providers icon in ribbon tab > Click Default link in Authentication Providers pop-up > Edit Authentication pop-up > IIS Authentication Settings > Integrated Windows Authentication > Select Negotiate (Kerberos)]


Note: As per me first option i.e. set anonymous access is best one.


4. Master page branding or UI change in SharePoint 2010

[Note: It’s was my personal experience]
I tried to change the HTML code of default.master or V4.master page/file using SharePoint 2010 Designer (SPD).
SPD reflected all changes, but when I browsed any content page, it didn’t displayed the desired changes.

Solution [as per me]:
I created a copy of default.master or V4.master and renamed it as per requirement. Made all the required HTML changes in it and saved it. Right clicked on the new custom master page and selected the Set as Default Master Page option. Changes get reflected in both SPD and all the browsed content pages.


5. How to hide first tab of SharePoint 2010 site

We need to add following CSS class to hide first tab of SharePoint 2010 site:

.s4-tn li.static:first-child{ 
display: none; 
}


Why we need to hide the first tab???
Ans: There is well known tab selection issue in SharePoint 2010. When we select first tab, second tab always remain selected (wrong tab selection as per UI). To solve this issue, I made the first tab invisible and made the second tab as home page tab. So by this when user clicks the first visible tab, he actually clicks the second tab and hence there is no UI confusion regarding tab selection.



6. Error :
Error occurred in deployment step 'Retract Solution': A deployment or retraction is already under way for the solution "MySolution.wsp", and only one deployment or retraction at a time is supported.

Solution:
a. Enumerates all pending and active deployments in the farm using following command:
stsadm -o enumdeployments

b. Cancel the troublesome Solution that was causing problem [specify the Solution GUID using above command]:
stsadm -o canceldeployment -id <solution GUID>


Reference:
SharePoint deployment or retraction issue



Friday, October 22, 2010

Display SharePoint ListItem's Attachments

Steps to create a separate page to display all the attachments of a particular SPListItem using SharePoint Designer:

1. Create an ASPX page using SharePoint Designer (SPD).



2. Add a DataView control in page in-between HTML form tag.
Note: First save the page then add control.



3. Select the Data Source Library.
Select your SharePoint List (in my case it is MyTest SPList). Open its context menu and select Show Data


4. Select columns you want to keep in Data Source Details.



5. Insert Selected Fields as Single Item View



6. Now some code changes:
a. Add some CSS style above closing head tag [optional]
<style type="text/css">
.ms-vb a
{
    font-family:Verdana;
    font-size:x-small;
}
</style>
</head>

b. Place your selected columns/fields
Location followig code snippet:
<xsl:template name="dvt_1.rowview">
<tr>

and insert following code in-between them:

<xsl:template name="dvt_1.rowview">[Original code - 1]
<tr style="color:maroon;font-weight:bold; font-family:Tahoma; font-size:small;">
    <td>
        Attachments                       
    </td>
</tr>
<tr class="ms-alternating" style="font-family:Tahoma; font-size:x-small;">
    <td>
        SharePoint ListItem ID - <b><SharePoint:FieldValue FieldName="ID" ControlMode="Display" runat="server" Visible="true" /></b>
    </td>
</tr>             
<tr class="ms-formbody" style="font-family:Tahoma; font-size:xx-small;">
    <td>
        <SharePoint:AttachmentsField ControlMode="Display" FieldName="Attachments" runat="server" Visible="true"/>
    </td>
</tr>
<tr style="display:none;">[Original code - 2]

Note-Here we are hiding the existing TR row


c. Hide paging control
Locate following code snippet:

<td nowrap="" class="ms-paging" align="right">

and hide that TD.
changed snippet:

<td style="display:none;" nowrap="" class="ms-paging" align="right"> 


7. Now open the page in browser and passed SPListItem as query string.
example: http://[server-name]:[port-number]/[page-name].aspx?ID=1


Tuesday, September 14, 2010

Code to search files with particular extension in SharePoint's Web Application

Requirement:
To search files with particular extension [here *.doc as example].

Here to achieve the above requirement I used SharePoint's Object Model.

I downloaded those searched files to a particular folder.
Beside printing the searched files result in console and I am also logging it in a Log file.


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

namespace SearchFile
{
    class Program
    {
        static void Main(string[] args)
        {
            //Get folder path
            string directoryPath
                = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
                , "MyFolder");

            //Create directory if it not exist
            if (!(Directory.Exists(directoryPath)))
                Directory.CreateDirectory(directoryPath);

            //SPFile myFile = null;
            byte[] binFile;
            string filename = string.Empty;
            FileStream fs = null;
            BinaryWriter bw = null;
            SPDocumentLibrary library = null;
            string fileExtension = ".doc";
            string siteURL = "http://[server-name]:[port-number]";
            StringBuilder filesLog = new StringBuilder();

            using (SPSite site = new SPSite(siteURL))
            {
                foreach (SPWeb web in site.AllWebs)
                {
                    foreach (SPList list in web.Lists)
                    {
                        if (list.BaseType == SPBaseType.DocumentLibrary)
                        {
                            library = (SPDocumentLibrary)list;
                            SPFolder folder = library.RootFolder;
                            ArrayList foldersList = new ArrayList();
                            foldersList.Add(folder);

                            foldersList = getFolders(folder, foldersList);

                            //foreach (SPListItem oListItem in library.Items)
                            foreach (SPFolder fold in foldersList)
                            {
                                foreach (SPFile myFile in fold.Files)
                                {
                                    //Download file in file system
                                    //myFile = oListItem.File;
                                    if (myFile.Name.EndsWith(fileExtension,
                                        StringComparison.InvariantCultureIgnoreCase))
                                    {
                                        binFile = myFile.OpenBinary();

                                        //Generate file name
                                        //filename = Path.Combine(directoryPath, myFile.Name);
                                        filename 
                                           = Path.Combine(directoryPath, 
                                                          myFile.Url.Replace("/", "_"));

                                        //Do file write operation
                                        fs 
                                          = new FileStream(filename, 
                                                FileMode.Create, FileAccess.ReadWrite);
                                        bw = new BinaryWriter(fs);
                                        bw.Write(binFile);
                                        bw.Close();

                                        filesLog.Append(string.Concat(web.Url, "/", 
                                                        myFile.Url, ","));
                                        Console.WriteLine(string.Concat(web.Url, "/",
                                                        myFile.Url));

                                    }//End file extension check 
                                }//End All SPFiles
                            }//End All SPFolders
                        }//End check DocumentLibrary
                    }//End All Lists
                }//End AllWebs
            }//End SPSite

            string[] lines = filesLog.ToString().Split(new char[] { ',' });
            System.IO.File.WriteAllLines(directoryPath + "/LOG_List.txt", lines);

            Console.WriteLine("Press any key to Exit...");
            Console.ReadLine();
        }

        //Recursive function to get all nested SPFolders
        static ArrayList getFolders(SPFolder folder, ArrayList foldersList)
        {
            foreach (SPFolder subfolder in folder.SubFolders)
            {
                foldersList.Add(subfolder);
                foldersList = getFolders(subfolder, foldersList);
            }
            return foldersList;
        }
    }
}


Thursday, August 19, 2010

Impersonation in Console/Windows Application

In this post I tried to cover the way to implement Impersonation in Console or Windows application. In Web application by setting Impersonation="True" in web.config we can do Impersonation but in Windows/Console it is not that straight-forward.

Here in Windows/Console we have to perform following steps [as per me]:
1. Write un-managed LogonUser function that will return UserToken based on passed input parameters
2. Get UserToken using LogonUser function
3. Pass UserToken to WindowsIdentity's constructor
4. Do the Impersonation
5. Do the required stuff using Impersonated Identity
6. Undo the Impersonation [Important]


Code Snippet:


using System;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.InteropServices;
using System.Security.Principal;

namespace ImpersonationSample
{
class Program
{
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername,
String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);


static void Main(string[] args)
{
IntPtr tokenHandle = new IntPtr(0);

const int LOGON32_PROVIDER_DEFAULT = 0;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;

tokenHandle = IntPtr.Zero;

string userName = "UserName";
string domainName = "DomainName";
string password = "UserPassword";

// Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser(userName, domainName, password,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
ref tokenHandle);

// Retrieve the Windows identity using the specified token.
WindowsIdentity windowsIdentity = new WindowsIdentity(tokenHandle);

// Create a WindowsImpersonationContext object
// by impersonating the Windows identity.
WindowsImpersonationContext impersonationContext =
windowsIdentity.Impersonate();


string connectionString =
"Data Source=[Server-Name];" +
"Initial Catalog=[Database-Name];" +
"Trusted_Connection=True;" +
"Integrated Security=SSPI;" +
"User Id=[DomainName\\UserName];" +
"password= [UserPassword]";

using (SqlConnection cn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM MyTable", cn);
cn.Open();
SqlDataReader rdr
= cmd.ExecuteReader(CommandBehavior.CloseConnection);
rdr.Read();
Console.WriteLine(rdr[0].ToString()); //read a value
}

Console.WriteLine("Name of the identity after impersonation: "
+ WindowsIdentity.GetCurrent().Name + ".");
Console.WriteLine(windowsIdentity.ImpersonationLevel);


// Stop impersonating the user.
impersonationContext.Undo();

// Check the identity name.
Console.Write("Name of the identity after performing an Undo on the");
Console.WriteLine(" impersonation: " +
WindowsIdentity.GetCurrent().Name);

Console.ReadLine();
}
}
}





References:
MSDN Impersonation 1
MSDN Impersonation 1
MSDN Impersonation 1
SQL Connection String Types

Thursday, March 18, 2010

SPFolder related operations in SharePoint

1) Get SPListItem(s) of a particular SPFolder


SPList splist;
SPFolder spfolder; //Get the required folder instance
SPQuery spquery = new SPQuery();
spquery.Query = string.Empty;
spquery.Folder = spfolder;
spquery.ViewAttributes = "Scope=\"Recursive\""; //For nested folder structure

SPListItemCollection itemCol = splist.GetItems(spquery)


2) Create a SPListItem based on a custom ContentType or SPFolder ContentType

SPWeb spweb; //get the SPWeb instance
SPContentType myCType = splist.ContentTypes["Custom content type"];
SPList splist = spweb.Lists["My SPList"];
SPListItem splistitem = splist.Items.Add();
splistitem["ContentTypeId"] = myCType.Id;
splistitem.Update();

splistitem["Title"] = "New Item";
splistitem.Update();


3) Add a SPListItem in a particular SPFolder

SPWeb spweb; //get the SPWeb instance
SPContentType myCType = splist.ContentTypes["Custom content type"];
SPList splist = spweb.Lists["My SPList"];
//get folder instance
SPFolder spfolder = splist.Folders[1];
SPListItem splistitem
= splist.Items.Add(spfolder.ServerRelativeUrl
, SPFileSystemObjectType.File, null);

splistitem["ContentTypeId"] = myCType.Id;
splistitem.Update();

splistitem["Title"] = "New Item";
splistitem.Update();

Image Preview functionality in SharePoint

Question:
How to display the Image preview without actually uploading the file in SharePoint?

Solution:
To check the image preview we can temporary move/place the file in Layout folder. Then pass URL in following format to Image control:
"/_layouts/images/MYFOLDER/MyImageName.jpg

After checking the Image preview and final upload of image file, we can delete the temporary image file from 12 hive.

Code snippet (comments are self-explanatory):


FileUpload FileUploadImage; //FileUpload control to select image file
Image myImage; //Image control to be used for preview functionality

//Getting 12 hive path through SPUtility.GetGenericSetupPath() function
string folderPath =
Microsoft.SharePoint.Utilities.SPUtility.GetGenericSetupPath("TEMPLATE")
+ "\\IMAGES\\MYFOLDER\\";

//Check folder path
if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);

//Copy the image file to a temporary folder in 12 hive
File.WriteAllBytes(folderPath + FileUploadImage.FileName,
FileUploadImage.FileBytes);

/* //File.Copy() will not work in case of remote image upload
File.Copy(FileUploadImage.PostedFile.FileName,
folderPath + FileUploadImage.FileName, true);
*/

//Set the URL of image control
myImage.ImageUrl =
"/_layouts/images/MYFOLDER/" + FileUploadImage.FileName;


Note: In a similar manner we can preview media file (like *.wmv) before actual upload in SharePoint.

Custom RSS Feed in SharePoint

SharePoint provides SPList’s level RSS Feed url [SPList Toolbar > Actions > View RSS Feed].
http://<server-name:port>/_layouts/listfeed.aspx?List=List_GUID

In above URL by specifying List’s GUID we can get feeds for all records (irrespective of any SPView or of Default View).

Now consider a scenario where we want SPView specific feeds.

In File System, ListFeed.aspx file is placed at following:
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\ListFeed.aspx

ListFeed.aspx refers Microsoft.SharePoint.ApplicationPages.ListFeed.cs class file. Using Reflector we can get the idea that ListFeed.aspx can accept 3 query strings as parameters: List GUID, Meeting Instance ID and View GUID.


Guid guid = new Guid(base.Request.QueryString.GetValues("List")[0]);
string[] values = base.Request.QueryString.GetValues("InstanceID");
string g = base.Request.QueryString["View"];


ListFeed.cs is using following function to get the feeds:

base.spList.WriteRssFeed(base.Response.OutputStream,
base.meetingInstanceId, this.spView);


MSDN Description of WriteRssFeed function:

public void WriteRssFeed (
Stream outputStream,
int meetingInstanceId,
SPView spView
)

Parameters
outputStream : A Stream object that represents the document stream.
meetingInstanceId : An integer value that represents the meeting instance.
spView :An SPView object that represents the view.


WriteRssFeed supports 3 overload methods:
SPList.WriteRssFeed(Stream) :
Writes the RSS feeds from the list to the specified document stream.

SPList.WriteRssFeed (Stream, Int32) :
Writes the RSS feeds from the list that are associated with the specified meeting to the specified document stream.

SPList.WriteRssFeed (Stream, Int32, SPView) :
Writes the RSS feeds from the list that are associated with the specified meeting and view to the specified document stream.

So if we want View specific feed then we have to specify all 3 parameters, but here comes the issue: what does Meeting Instance ID mean and from where we get this value?



Now to get the SPView specific feed, we can write custom RSS Feed. I referred this post- blah.winsmarts.com. I modified the original code little bit. I created a application page and instead of writing inline server code I created a class library so that I can debug the page.

HTML Code:

<%@ Page Language="C#"
Inherits="MyNameSpace.MyFeed,MyNameSpace,
Version=1.0.0.0,Culture=neutral,PublicKeyToken=1d5ac09ccd41620f" %>


C# Code:

using System;
using System.Web;
using System.Text;
using Microsoft.SharePoint;
namespace MyNameSpace
{
public class MyFeed
: Microsoft.SharePoint.WebControls.UnsecuredLayoutsPageBase
{
public void Page_Load()
{
try
{
Response.Write(GetRSSFromListView(
Request.QueryString["List"],
Request.QueryString["View"]));
}
catch (Exception ex)
{
Response.Write("<pre>");
Response.Write(ex.ToString());
Response.Write("</pre>");
}
}
private static string GetRSSFromListView(string strListGUID,
string strViewGUID)
{
StringBuilder sb = new StringBuilder();
sb.Append("<?xml version=\"1.0\"?>");
sb.Append("<rss version=\"2.0\">");

using (SPSite site = new SPSite(SPContext.Current.Web.Url))
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[new Guid(strListGUID)];
SPView view = null;
if (strViewGUID != null)
view = list.Views[new Guid(strViewGUID)];
else
view = list.DefaultView;

sb.Append("<channel>");
AddTag("title", list.Title, sb);
AddTag("description", list.Description, sb);

SPListItemCollection items = list.GetItems(view);
foreach (SPListItem item in items)
{
sb.Append("<item>");
AddTag("title", item["LinkTitle"].ToString(), sb);
AddTag("link", list.RootFolder.Url
+ "/DispForm.aspx?ID=" + item.ID, sb);
sb.Append("<description>");
foreach (string viewField in view.ViewFields)
{
if (viewField != "LinkTitle")
{
AddTag(
viewField.Replace("_x0020_", " "),
HttpContext.Current.Server.HtmlEncode
(item.GetFormattedValue(viewField)),
sb);
}
}
sb.Append("</description>");
sb.Append("</item>");
}
sb.Append("</channel>");
sb.Append("</rss>");
}
return sb.ToString();
}


private static void AddTag(string tagText,
string tagValue, StringBuilder sb)
{
sb.Append("<");
sb.Append(tagText.Replace(" ", "_"));
sb.Append(">");
sb.Append(HttpContext.Current.Server.HtmlEncode(tagValue));
sb.Append("</");
sb.Append(tagText.Replace(" ", "_"));
sb.Append(">");
}
}
}


Now if we use the above custom RSS Feed page URL and pass it to SharePoint’s out-of-box RSS Viewer Webpart, then we will get following error:

The RSS webpart does not support authenticated feeds.

Solution -
Changing to Kerberos authentication
1. On the Central Administration page, click Application Management.
2. Under the Application Security section, click Authentication Providers.
3. Click the Default provider, and change Integrated Widows authentication from NTLM to Negotiate (Kerberos).

OR
We can use custom RSS Viewer WebPart, which is already developed and uploaded at : philwicklund.com


References:
RSS Feed
how-to-get-moss-2007-rss
RSS Reader
Technet
MSDN

Wednesday, November 25, 2009

Tuesday, November 24, 2009

Sharepoint Tips n Tricks - Part 2

In continuation with earlier post -
Sharepoint Tips n Tricks

1) Check whether a given SPField exist or not before fetching value from it:


string columnValue = string.Empty;
string columnInternalName = string.Empty;
string fieldName = "Myfield";
SPListItem listItem; //Code to get SPListItem

//Check required SPField exist or not
if (listItem.ParentList.Fields.ContainsField(fieldName))
{
//Get internal name of SPField
columnInternalName = listItem.ParentList.Fields[fieldName].InternalName;

//Fetch column value based on internal name
if (listItem[columnInternalName] != null)
columnValue = listItem[columnInternalName].ToString();
}



2) SharePoint 2007 recommended guidelines for managing site collections, site, lists, and documents according to business needs:

· 50,000 site collections per content database

· 500 MB per site collection (default quota maximum)

· 50 MB file size limit (recommended) up to 2 GB (maximum)

· 2000 items per list view


3) Check whether page is in Edit Mode or not


if (Microsoft.SharePoint.SPContext.Current.FormContext.FormMode == SPControlMode.Display)
{
// your code to support display mode
}
else if(Microsoft.SharePoint.SPContext.Current.FormContext.FormMode = SPControlMode.Edit)
{
// your code to support edit mode
}


OR


WebPartManager wp = WebPartManager.GetCurrentWebPartManager(Page);

if (wp.DisplayMode == WebPartManager.BrowseDisplayMode)
btnLink.InnerText = "Edit Page";
else if (wp.DisplayMode == WebPartManager.DesignDisplayMode)
btnLink.InnerText = "Exit Edit Mode";
else
btnLink.Visible = false;



Reference...
http://www.codeproject.com/KB/sharepoint/SwitchWPMode.aspx

http://mystepstones.wordpress.com/2008/09/23/detecting-the-current-mode-displayedit/


4) SPFeature to deploy page in a SharePoint site


Feature.xml
<?xml version="1.0" encoding="utf-8"?>
<Feature Id="f08674ee-2b0e-41aa-8d28-24e788d03c11"
Title="PageDeployment"
Description="Description for PageDeployment"
Version="12.0.0.0"
Hidden="FALSE"
Scope="Web"
DefaultResourceFile="core"
xmlns="http://schemas.microsoft.com/sharepoint/">
<ElementManifests>
<ElementManifest Location="elements.xml"/>
<ElementFile Location="MyPage.aspx" />
</ElementManifests>
</Feature>


Elements.xml
<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Module Name="Pages" Path="" Url="">
<File Name=" MyPage.aspx" Url=" MyPage.aspx" IgnoreIfAlreadyExists="FALSE" NavBarHome="True"></File>
</Module>
</Elements>

Code to download document from SharePoint Document Library

Following code snippet demonstrate the way to download a MS Word document (or any file) from SharePoint SPDocumentLibrary-


string siteURL = "http://localhost:80/"; //Write valid site URL
//Get SPSite and SPWeb instance
using (SPSite spSite = new SPSite(sireURL))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
//Get time stamp to download file with unique name
string strFileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");

//Get folder path
string directoryPath =
Path.Combine(Environment.GetFolderPath
(Environment.SpecialFolder.LocalApplicationData),
"MyFolder");

//Create directory if it not exist
if (!(Directory.Exists(directoryPath)))
{
Directory.CreateDirectory(directoryPath);
}

//Get template url
string documentUrl; //Write valid document URL

//Download file in file system
SPFile myFile = spWeb.GetFile(documentUrl);
byte[] binFile = myFile.OpenBinary();

//Generate file name
filename = Path.Combine(directoryPath, strFileName + ".doc");

//Do file write operation
FileStream fs =
new FileStream(filename, FileMode.Create, FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(binFile);
bw.Close();
}
}

MSMQ operations in C#

Following code snippet demonstrate the way to do some common operations with Microsoft Message Queuing (MSMQ)-

1) Send message in MSMQ -


string queueName = @".\Private$\MyMSMQ";
string myMessage = "Hello World";
MessageQueue messageQueue = null;
Message oMsg = null;

//Sending Messages to MSMQ
if (MessageQueue.Exists(queueName))
{
messageQueue = new MessageQueue(queueName);

oMsg = new Message(myMessage);
messageQueue.Send(oMsg);
}
else
{
//Create the MessageQueue
messageQueue = MessageQueue.Create(queueName);
//Set Queue permission
//messageQueue.SetPermissions("Everyone", MessageQueueAccessRights.FullControl,
// AccessControlEntryType.Set);
messageQueue.SetPermissions("Everyone",
MessageQueueAccessRights.PeekMessage |
MessageQueueAccessRights.ReceiveMessage |
MessageQueueAccessRights.DeleteMessage |
MessageQueueAccessRights.WriteMessage,
AccessControlEntryType.Set);

oMsg = new Message(myMessage);
messageQueue.Send(oMsg);
}



2) Receive Message from MSMQ -


string myMessage= string.Empty;
string queueName = @".\Private$\MyMSMQ";

//Receiving Messages from MSMQ
MessageQueue messageQueue = new MessageQueue(queueName);

//To keep a check that if no messages present in MSMQ,
//control should return back in 1 second.
TimeSpan timeout = new TimeSpan(1);
Message message = null;

//Get all the messages present in the MSMQ and iterate through it.
MessageEnumerator enumerator = messageQueue.GetMessageEnumerator2();

if (enumerator.MoveNext())
message = enumerator.RemoveCurrent(timeout);

if (message != null)
{
messageBody = message.Body.ToString();
}




3) Display all the messages present in the MSMQ (without removing messages from queue)


StringBuilder allMessages = new StringBuilder();
string queueName = @".\Private$\MyMSMQ";

//Enumerating Messages from MSMQ
MessageQueue oMq = new MessageQueue(queueName);

foreach (Message message in oMq)
{
stringBuilder.Append(message.Body + ";");
}



4) Deletes all the messages contained in the MSMQ queue


string queueName = @".\Private$\MyMSMQ";

//Deletes all the messages contained in the MSMQ queue
MessageQueue messageQueue = new MessageQueue(queueName);
messageQueue.Purge();



Nice link to refer -
Use Microsoft Message Queuing in C# for inter-process communication

Thursday, October 8, 2009

Code to add SPUser in SPGroup

Following code snippet demonstrate the way to programmatically add SPUser in SPGroup...





try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite spSiteTemp = new SPSite(SPContext.Current.Web.Url))
using (SPWeb spWebTemp = spSiteTemp.OpenWeb())
{
spWebTemp.AllowUnsafeUpdates = true;

SPGroup spGroup = spWebTemp.SiteGroups["MySPGroup"];

SPUser spUser = spWebTemp.EnsureUser("DomainName\" + msUser.UserName);

//Adding group name in temporary arraylist to check SPUser's existing group.
ArrayList arrayListGroups = new ArrayList();
foreach (SPGroup tempGroup in spUser.Groups)
{
arrayListGroups.Add(tempGroup.Name.ToLower());
}

if ((spUser.Groups.Count < 1)
|| ((spUser.Groups.Count > 1)
&& (!arrayListGroups.Contains("myspgroup"))))
{
spGroup.AddUser(spUser);
}

spWebTemp.AllowUnsafeUpdates = false;
}
});
}
catch (SPException)
{
throw;
}


Populate SharePoint's SPList with records from MSExcel file

In this post, I will focus on the way to retrieve the records from MS Excel file and then populate it in SPList of SharePoint.


Code snippet(comments are self-explainatory)...


int count = 0;
try
{
SPUserToken sysToken = SPContext.Current.Site.SystemAccount.UserToken;
using (var spSite = new SPSite(SPContext.Current.Site.ID, sysToken))
{
using (var spWeb = spSite.OpenWeb(SPContext.Current.Web.ID))
{
//Get Interviewers SPList
SPList oList = spWeb.Lists["ListName"];

#region uploading Excel

//Here for saving file in FileSystem, creating time stamp
string strFileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");
//FileUpload file;
string strFileType
= System.IO.Path.GetExtension(file.PostedFile.FileName)
.ToString().ToLower();

//Check file type
if (strFileType == ".xls" || strFileType == ".xlsx")
{
//Create Directory specified in parameter for downloading
string directoryPath
= HttpContext.Current.Server.MapPath("~/UploadedExcel");

if (!(System.IO.Directory.Exists(directoryPath)))
{
System.IO.Directory.CreateDirectory(directoryPath);
}

//Save file in FileSystem
file.SaveAs(HttpContext.Current.Server.
MapPath("~/UploadedExcel/" + strFileName + strFileType));
}
else
{
throw new FormatException("Only excel file is allowed");
}

string strNewPath
= HttpContext.Current.Server.MapPath("~/UploadedExcel/" +
strFileName + strFileType);

//Connection String to Excel Workbook
string connectionString = string.Empty;
if (strFileType.Trim() == ".xls")
{
connectionString
= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
strNewPath +
";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connectionString
= "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
strNewPath +
";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}


OleDbConnection conn = new OleDbConnection(connectionString);
//This will open excel file
conn.Open();
//Get the Excel Sheet name from Config
string sheetName = "Sheet1";
if (!string.IsNullOrEmpty(System.Configuration.ConfigurationSettings.
AppSettings["ExcelSheetName"]))
{
sheetName = System.Configuration.ConfigurationSettings.
AppSettings["ExcelSheetName"];
}

string strSQL = "SELECT * FROM [" + sheetName + "$]";

OleDbCommand cmd = new OleDbCommand(strSQL, conn);
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);

spWeb.AllowUnsafeUpdates = true;
SPListItem listItem = null;

foreach (DataRow dr in ds.Tables[0].Rows)
{
//Create new SPListItem
listItem = oList.Items.Add();

listItem["FirstName"]
= dr["First Name"] != null ? dr["First Name"].ToString() : null;
listItem["LastName"]
= dr["Last Name"] != null ? dr["LastName"].ToString() : null;

listItem.Update();

listItem = null;
}

spWeb.AllowUnsafeUpdates = false;

conn.Close();
//Delete the saved excel file from FileSystem
System.IO.File.Delete(strNewPath);

#endregion

//Increment the record count
count = oList.Items.Count;
}
}

return count;
}
catch (SPException)
{
throw;
}

Login pop-up in SharePoint

If you gets login pop-up whenever you opens any SharePoint page in Internet Explorer (IE), then solve this issue we need to change following IE settings...

Add the SharePoint site to the list of Local Intranet (IE7/8).
Steps:



1) In Internet Explorer, on the Tools menu, click Internet Options.
2) On the Security tab, in the Select a Web content zone to specify its security settings box, click Local Intranet, and then click Sites.
3) Clear the Require server verification (https:) for all sites in this zone check box.
4) In the Add this Web site to the zone box, type the URL to your site, and then click Add.
5) Click Close to close the Local Intranet dialog box.
6) Click OK to close the Internet Options dialog box.


Reference--
MSDN Forum

Wednesday, September 16, 2009

Sun One Active Directory in SharePoint

In this post I will focus how to use Sun One Active Directory (AD) in SharePoint.
Steps:














1) Install Sun one Server 5.2 and add some users:
ou=SPUsers
uid=JSmith, ou=SPUsers, dc=CompanyName,dc=co, dc=in



2) On central admin site,
Go to Application management -> Sharepoint Web Application Management section -> Web application list.
Select the web application which you want to bind to Sun one DS.
Click on Authentication providers under Application Security section in Application Management.



3) Click on the zone for which you want to do configuration. Then make the settings as per the screenshot below, and click on Save.





4) Add the following code to web.config files of the website as well as central admin site.


<membership defaultProvider="LDAP">
<providers>
<add name="LDAP"
type="Microsoft.Office.Server.Security.LDAPMembershipProvider,
Microsoft.Office.Server, Version=12.0.0.0, Culture=neutral,
PublicKeyToken=71E9BCE111E9429C"
server="ServerName"
port="15000"
useSSL="false" userDNAttribute ="entryDN"
userNameAttribute ="uid"
userContainer="ou=SPUsers,dc=CompanyName,dc=co,dc=in"
userObjectClass="inetorgperson"
userFilter="(ObjectClass=inetorgperson)" scope="Subtree"
/>
</providers>
</membership>



5) Add a user with Full Control on the Web application to enable initial logon to the site collections and to perform administrative tasks. To add a user, click Add Users on the Policy for Web Application page, and select a zone.



Click Next.

6) Enter a valid user in Users text box like provider name: username as shown below:



Verify name using Check names and then choose permissions.



Click on Finish.



7) Now you can login into the site using the above added username.



8) Permissions can be given to other users by using People and Groups link. User name has to be entered in the form of providerName:username.

References:
Sun One AD 1

Sun One AD 2

For ADAM refer following links:

SharePoint PeoplePicker Behavior with ADAM Users

How to use WSS v3 with ADAM for user authentication

Google