Monday, December 16, 2013

Unknown server tag 'SharePoint:ScriptBlock'.

Error: Unknown server tag 'SharePoint:ScriptBlock'.

Issue: You will get above error when you use the application page in SharePoint 2013 using <SharePoint:ScriptBlock> and try to use that in SharePoint 2010.

Cause: ScriptBlock class is not available in SharePoint 2010 & 2007.

Resolution: Replace the block with <script type="text/javascript">

Sunday, December 15, 2013

This operation can be performed only on a computer that is joined to a server farm by users who have permissions in SQL Server to read from the configuration database. To connect this server to the server farm, use the SharePoint Products Configuration Wizard, located on the Start menu in Microsoft SharePoint 2010 Products.

Error: This operation can be performed only on a computer that is joined to a server farm by users who have permissions in SQL Server to read from the configuration database. To connect this server to the server farm, use the SharePoint Products Configuration Wizard, located on the Start menu in Microsoft SharePoint 2010 Products.

Cause: Got above error when I tried to access my SharePoint site and Central administration. The error says that current user is not able to access the database. Everything was working fine until I've crashed my VMWare and restarted.

Resolution:
1. Open Services.msc
2. Restarted SQL Server (SHAREPOINT) service
3. Noticed that the following services was disabled. Enabled both the service.
SQL Server Agent (SHAREPOINT)
SQL Server Browser

Friday, December 6, 2013

Close modal dialog after page validation passes

Requirement:
To open the default Create Group (newgrp.aspx) page as a dialog box from our custom page on a button click. Close the modal dialog box after page submits.
We created a copy of newgrp.aspx page and used that page to achieve this.

Issues we had:
1. Default “create group” page redirects to the people.aspx page after successful page submission.
2. Closing the dialog on Window.unload worked fine, but the dialog got closed even when the validation fails as validation refresh the page.

Solution:
Create an HTTPModule to check the current page and previous page details though HTTP events. Below is the HttpModule code we used to achieve this.

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

namespace DSPModule
{
    public class DynamicModule : IHttpModule
    {

        string strParentPageURL = string.Empty;
        string strCurrentPageURL = string.Empty;

        public DynamicModule()
        {
        }

        public String ModuleName
        {
            get { return "DSPDynamicModule"; }
        }

        // In the Init function, register for HttpApplication events by adding your handlers.
        public void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
        }
        void context_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            HttpContext currentContext = HttpContext.Current;
            Page page = currentContext.CurrentHandler as Page;
            if (page != null)
            {
                page.LoadComplete += new EventHandler(page_LoadComplete);
            }
        }
        void page_LoadComplete(object sender, EventArgs e)
        {        
             HttpContext currentContext = HttpContext.Current;
             if(currentContext.Request.UrlReferrer != null)
                strParentPageURL = currentContext.Request.UrlReferrer.ToString().Trim().ToUpper();

             strCurrentPageURL = currentContext.Request.Url.AbsolutePath.ToString().Trim().ToUpper();
             if (strParentPageURL.Contains("/_LAYOUTS/DSPHANDLER/DSPNEWGRP.ASPX") && strCurrentPageURL.Contains("/_LAYOUTS/PEOPLE.ASPX") && strParentPageURL.Contains("?ISDLG=1"))
             {
                 HttpContext.Current.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
                 HttpContext.Current.Response.Flush();
                 HttpContext.Current.Response.End();
             }
        }
        public void Dispose()
        {

        }
    }
}

Make sure that you add the following entry in the web.config file of the web application at path "configuration/system.webServer/modules"
<add name="DSPDynamicModule" type=" DSPModule.DynamicModule, DSPModule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=fa63464975c1a198" />

Feel free to discuss if you have better way of doing this.


Thursday, October 17, 2013

Move dll to Gac using powershell

Developers during debugging their code, move their dll to gac and reset IIS. To automate this and save time, we can create a powershell script.


[System.Reflection.Assembly]::Load("System.EnterpriseServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
$publish = New-Object System.EnterpriseServices.Internal.Publish $publish.GacInstall("D:\Prasath\Workouts\Lookup\bin\Debug\SP.MyContent.dll")
iisreset

Save the above code as "somefilename.ps1"
To execute, right click the saved file and select "Run with Powershell"

Tuesday, October 15, 2013

Connect application service to a web application programmatically

The following code will connect a custom user profile application service to a web application.
(SharePoint 2010)


           SPSite site = new SPSite("http://current site url");

           //Get all Service Proxies in the farm
           SPServiceProxyCollection farmServices = SPFarm.Local.ServiceProxies;

            // Iterate all the proxies
            foreach (SPServiceProxy service in farmServices)
            {
                SPServiceApplicationProxyCollection serviceApplicationColl = service.ApplicationProxies;
                foreach (SPServiceApplicationProxy serviceApp in serviceApplicationColl.OfType<SPServiceApplicationProxy>())
                {
                    if (serviceApp.DisplayName == "My Custom User Profile" && serviceApp.TypeName.ToLower().Contains("user profile service"))
                    {
                        //Add the service proxy to the web application
                        site.WebApplication.ServiceApplicationProxyGroup.Add(serviceApp);
                       
                         // update the application proxy group
                        site.WebApplication.ServiceApplicationProxyGroup.Update();

                         //update the web application
                        site.WebApplication.Update();
                 
                    }
                }
            }


Thursday, October 3, 2013

Check SharePoint Version and read User Profile Property value programmatically

[SharePoint 2010; SharePoint 2013]


using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.Server.UserProfiles;
using System.Linq;
using System.Collections;

namespace GetProfileProperty
{
    class Program
    {
        //Declare SKU keys of each SharePoint version
        const string SHAREPOINT2010FOUNDATION = "BEED1F75-C398-4447-AEF1-E66E1F0DF91E";
        const string SHAREPOINT2010STANDARD = "3FDFBCC8-B3E4-4482-91FA-122C6432805C";
        const string SHAREPOINT2010ENTERPRISE = "D5595F62-449B-4061-B0B2-0CBAD410BB51";
        const string SHAREPOINT2013STANDARD = "C5D855EE-F32B-4A1C-97A8-F0A28CE02F9C";
        const string SHAREPOINT2013ENTERPRISE = "B7D84C2B-0754-49E4-B7BE-7EE321DCE0A9";
        const string SHAREPOINT2013FOUNDATION = "9FF54EBC-8C12-47D7-854F-3865D4BE8118";
           

        static void Main(string[] args)
        {
            string _skuID = string.Empty;
            string CurrentSPVersion = string.Empty;
            bool IsUserProfileServiceEnabled = false;
            string result = string.Empty;
            string PropertyName = "Unit System"; //User profile property name to get the value
            string siteURL = "http://siteURL";
            SPSite site = new SPSite(siteURL);

            SPFarm farm = site.WebApplication.Farm;

            //Get the SharePoint Products installed in current Farm
            IEnumerable<Guid> _guid = farm.Products;

            //Iterate each product to find the version installed
            foreach (var item in _guid)
            {
                _skuID = item.ToString();
                //Condition true if the version installed is Enterprise/Standard
                if (_skuID.Equals(SHAREPOINT2010ENTERPRISE, StringComparison.CurrentCultureIgnoreCase) || _skuID.Equals(SHAREPOINT2010STANDARD, StringComparison.CurrentCultureIgnoreCase) || _skuID.Equals(SHAREPOINT2013ENTERPRISE, StringComparison.CurrentCultureIgnoreCase) || _skuID.Equals(SHAREPOINT2013STANDARD, StringComparison.CurrentCultureIgnoreCase))
                {
                    CurrentSPVersion = "SPServer";
                    break;
                }
                //Condition true if the version installed is Foundation
                if (_skuID.Equals(SHAREPOINT2010FOUNDATION, StringComparison.CurrentCultureIgnoreCase) || _skuID.Equals(SHAREPOINT2013FOUNDATION, StringComparison.CurrentCultureIgnoreCase))
                {
                    CurrentSPVersion = "SPFoundation";
                }

            }
            if (CurrentSPVersion == "SPServer")
            {
                    //Get the service applications installed in the web application
                    Microsoft.SharePoint.SPServiceContext spServiceContext = Microsoft.SharePoint.SPServiceContext.GetContext(site);
                    IEnumerable<SPServiceApplicationProxy> proxies = site.WebApplication.ServiceApplicationProxyGroup.Proxies;

                    foreach (var services in proxies)
                    {
                        //Check if the User Profile Service is enabled
                        if (services.TypeName == "User Profile Service Application Proxy")
                        {
                            IsUserProfileServiceEnabled = true;
                        }
                    }
                    if (IsUserProfileServiceEnabled)
                    {
                        Console.WriteLine("User profile for this web application is enabled");
                        Console.WriteLine(GetUserProfilePropertyValue(siteURL, PropertyName, true));
                    }
                    else
                    {
                        Console.WriteLine("User profile for this web application is NOT enabled");
                    }
                 
            }
            if (CurrentSPVersion == "SPFoundation")
            {
                Console.WriteLine("You have SP Foundation");
            }
         
        }

        /// <summary>
        /// Get the User Profile Property value
        /// </summary>
        /// <param name="property">User Profile Propery Name</param>
        /// <param name="isUserProfileEnabled">boolean</param>
        /// <returns></returns>
        public static string GetUserProfilePropertyValue(string siteURL, string property, bool isUserProfileEnabled)
        {
            string result = "";
            string CurrentWeb =siteURL;
            try
            {
                //Get the value from My Settings/User Information List if User Profile Service is not enabled
                if (!isUserProfileEnabled)
                {
                    using (SPSite site = new SPSite(CurrentWeb))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPList userInfoList = web.SiteUserInfoList;
                            SPUser user = web.EnsureUser(@"domainname\username");
                            SPListItem userItem = userInfoList.Items.GetItemById(user.ID);
                            result = userItem[property].ToString();
                        }
                    }
                }
                else
                {
                    //Read the user profile property value if user profile service application is enabled. Reads the value using User Profile Manager
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite site = new SPSite(CurrentWeb))
                        {
                            SPServiceContext context = SPServiceContext.GetContext(site);
                            UserProfileManager profileManager = new UserProfileManager(context);
                            string sAccount = @"domainname\username";
                            UserProfile userProfile = profileManager.GetUserProfile(sAccount);
                            ProfileSubtypePropertyManager psmanager = userProfile.Properties;

                            //Get the internal name from the display name
                            IEnumerable<string> PropertyInternalName = psmanager.Cast<ProfileSubtypeProperty>()
                                                                        .Where(r => r.DisplayName.ToLower() == property.ToLower())
                                                                        .Select(r => r.Name);
                            //Get the value of property
                            if(PropertyInternalName.Count()==1)
                                result = userProfile[PropertyInternalName.First().ToString()].Value.ToString();
                        }

                    });
                 
                }

            }
            catch (Exception)
            {
           
            }
            return result;
        }

    }
}

PS: Above is a console application and some of the values are hard-coded, you need to change the code accordingly to your requirement/environment.

Tags:
- programmatically retrieve user profile property value using property display name
- Check SharePoint version/edition programmatically


Add custom profile property in User Information List

Using SharePoint 2010;

Requirement: To add/read a custom profile property in My Settings page/ User Information List.

To read profile property and values:

            string fieldName = string.Empty;
            using (SPSite site = new SPSite("http://SiteURL"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList userInfoList = web.SiteUserInfoList;
                    SPUser user = SPContext.Current.Web.EnsureUser(login);
                    SPListItem userItem = userInfoList.Items.GetItemById(user.ID);

                    foreach (SPField field in userInfoList.Fields)
                    {
                        fieldName = field.Title;
                        Console.WriteLine(fieldName + "\t " + userItem[fieldName]);
                    }
                }
            }

To add a custom profile property:

//Create custom profile property
   SPField newTextfield = userInfoList.Fields.CreateNewField(SPFieldType.Text.ToString(), "Personal Web Site");                  
  userInfoList.Fields.Add(newTextfield);
  userInfoList.Update();

Few facts about My Settings Page:

1. Keep in mind that “My Profile” and “My Settings” are two completely different things.  My Profile is looking at information directly from the Profile Database.  My Settings is site specific, and is looking at information at the current site.

2. If the User Profile service application is not enabled when you visit the site initially, your data is retrieved from the Active directory and stored in the content database "User Information List"

3. User Information List is a hidden list. You can access it programmatically or using PowerShell.

4. In People and Group page (http://<sitecollection>/_layouts/people.aspx), it appears as a SharePoint list. Fields can be added or removed to suit the business needs.

5. List events are not raised on the User Information list type. There is no resolution as of now as per Microsoft. Refer: http://msdn.microsoft.com/en-us/library/aa979520.aspx

6. My Settings is the local site collection profile. The UserInfo table (DB instance of ‘User Information List’) is a table stored in the Content Database for each Site Collection.

7. If User Profile is not configured and there are no My sites, then we can use User Information List available per each Site Collection where minimal data is available, such as AD account, SID, Email, First name, last name.

8. Custom properties in User Information List can be added from ‘People and Groups’ site collection page by Site Collection Administrators.

Wednesday, July 31, 2013

Using JQuery in new form and edit form

Using jquery-1.8.2.min.js;

To get the instance of a control which does not have the title field in source view:(f12 view)

Criteria is a lookup field name and the client ID for that would be ctl00_m_g_0cf2a9f8_fc83_4e94_a96e_c4cb7d1d3e09_ctl00_ctl04_ctl09_ctl00_ctl00_ctl04_ctl00_BambooLookupPlus_x0028_1_x0029__x0020_Criteria. Using Client Id directly in the script is not recommended, so use the following syntax to get the Criteria field instance. Normally the ID value would have the field name suffixed.

//To get the field instance:
var criteria1field = $("[id$='Criteria']")[0];

//To disable field
$(criteria1field).attr('disabled', 'disabled');

//To enable field
$(criteria1field).removeAttr("disabled");

//Change event for Issue Type field
 $(criteria1field).bind("change", function() { //code goes here });




//wait for 5 seconds
setTimeout(function()
 {
  // code goes here

}, 5000);

//Set Criteria  field width and style   
$(criteria1field).css('width','70');
$(criteria1field).css("background-color","red")
$(criteria1field).css("font-face","bold")

//Set lookup field value
$(criteria1field).val("This is a sample value");

//To get the value of field that has title field in source view
var Severity = $("input[Title='Severity']").val();


Friday, June 21, 2013

Apply custom css file for default master page

For MOSS 2007;

To apply a custom stylesheet for a specific site.

1. Open the site in SPD
2. Checkout the master page, open, go to design view and open the Apply Styles panel.
Create Custom Style Sheet using SharePoint Designer

3. Select any style and click "Go To Code". This opens the core.css that it was mapped to by default.

Create Custom Style Sheet using SharePoint Designer

4. Modify the style and save the core.css file. This will popup a warning message. Click Yes. This will save customized core.css file in your local site and your master page will be applied with this custom css.

5. Check in the master page.

Wednesday, May 1, 2013

ICellProvider vs IRowProvider vs IListProvider vs IFilterProvider vs IWebPartField vs IWebPartRow vs IWebPartTable vs IWebPartParameters



Interfaces used to make web part connections.

ICellProvider: This API is now obsolete. Enables a Web Part to communicate with a Web Part that implements the ICellConsumer interface to work with a single value item.
IWebPartField : Defines a provider interface for connecting two server controls using a single field of data.

IRowProvider: This API is now obsolete. Enables a Web Part to send a row of data to a Web Part that implements the IRowConsumer, ICellConsumer, IFilterConsumer, or IParametersInConsumer interface.
IWebPartRow: Defines a provider interface for connecting two server controls using a single field of data.


IListProvider: This API is now obsolete. Defines events that a Web Part can implement so that it can provide an entire list (rowset) of data to another Web Part that implements the IListConsumer interface.
IWebPartTable: Defines a provider interface for connecting two server controls using an entire table of data.

IFilterProvider: This API is now obsolete. Used to communicate with a Web Part that implements IFilterConsumer interface to provide filter information to the consumer.
IWebPartParameters: Defines the contract a Web Parts control implements to pass a parameter value in a Web Parts connection.

Source: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webparts.aspx

Tuesday, April 23, 2013

Fast Search in SharePoint 2010


Advantages of using Fast Search in SharePoint 2010
1. Crawl BDC content with FAST.
2. Previewers – Display inline previews of Word, PowerPoint, and Excel files.
3. Indexing more documents
4. FAST can be configured for Enterprise edition only
5. Search enhancements based on user context Scopes Best Bets, visual Best Bets, and document promotions and demotions to a sub-group of employees.
6. Rich Web indexing support Indexing of wide variety of Web content, including Flash.

Using LINQ to SharePoint


The LINQ to SharePoint provider is a new feature in SharePoint 2010 that allows you to use a strongly-typed entity model and the language integrated query (LINQ) query syntax to query list data. Essentially, LINQ to SharePoint hides the complexity of developing CAML queries from developers, which can reduce development time and make code more readable. The LINQ to SharePoint provider converts the LINQ expressions into CAML queries at run time.

Using LINQ to SharePoint in your own solutions consists of three main steps:
  • Generate the entity classes. Before you can start writing LINQ queries against your SharePoint lists, you must create or generate the strongly-typed entity classes that represent your list data and lookup column relationships.
  • Develop the solution. After you add the entity classes to your Visual Studio 2010 project, you can write LINQ queries against the strongly-typed entities that represent your data model.
  • Run the solution. At run time, the LINQ to SharePoint provider dynamically converts your LINQ expressions into CAML queries, executes the CAML, and then maps the returned items to your strongly-typed data entities.
Although you can manually develop your entity classes, in most cases, you will want to use the SPMetal command line tool. This is included in SharePoint Foundation 2010 and can be found in the BIN folder in the SharePoint root. The SPMetal tool targets an individual SharePoint site and, by default, generates the following code resources:
  • A data context class that derives from DataContext. This is the top-level entity class. It represents the content of your site and provides methods that allow you to retrieve list entities. The data context class uses the EntityList<TEntity> class to represent the lists in your site, where TEntity is a class that represents a content type.
  • Classes that represent content types. These are marked with the ContentTypeAttribute. Content type classes are generated for implicit content types as well as content types that are explicitly defined on the site. For example, if a user adds a column to an existing list, the user is creating an implicit content type and a representative class will be generated.
  • Classes and properties that represent relationships between listsSPMetal can detect relationships based on lookup columns. Within the entity class that represents a content type, SPMetaluses the EntityRef<TEntity> class to represent the singleton side of a one-to-many relationship and the EntitySet<TEntity> class to represent the “many” side of one-to-many or many-to-many relationships (known as a reverse lookup). Properties that are mapped to a field in a related list are decorated with the AssociationAttribute.
Reference: 

Error: The type or namespace name ‘SharePoint’ does not exist in the namespace ‘Microsoft’(are you missing reference?)


Issue: I’ve got the above error when trying to run a simple code in the console application. Though added the Microsoft.SharePoint .dll from the following path C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.SharePoint.dll, was getting the error during debugging.
Resolution: Right click the Solution Explorer and click properties, In Application tab, .Net Frameworkf 4.0 Client Profile was selected by default, change it to .Net Framework 3.5 and debug again. Also change the Platform target in the Build tab to x64.

When to use ‘using’ and ‘dispose’ and when not to use in SharePoint


If you create your own SPSite object, you can use the Dispose method to close the object. However, if you have a reference to a shared resource, such as when the object is provided by the GetContextSite method in a Web Part, do not use either method to close the object. Using either method on a shared resource causes an Access Violation error to occur
Likewise, If you obtain an SPWeb object using OpenWeb or RootWeb, the best practice is to implement the using statement or the Dispose method to dispose of the object.
However, if you have a reference to a shared resource, such as when you obtain the Web site object from the SPContext object in a Web Part by using SPContext.Current.Web, do not use either method to close the object.

SharePoint 2010 Development Platform Stack

Wednesday, March 20, 2013

SharePoint Licensing - Client Access License (CALs)


Types of CALs:


·         User CAL
·         Device CAL 

User CAL:

     
      With the User CAL, you purchase a CAL for every user who accesses the server to use services such as file storage or printing, regardless of the number of devices they use for that access. Purchasing a User CAL might make more sense if your company employees need to have roaming access to the corporate network using multiple devices, or from unknown devices, or simply have more devices than users in your organization. You can go for User CAL if number of User is less than number of devices.

 Client Access License based on user

Device CAL:


     With a Device CAL, you purchase a CAL for every device that accesses your server, regardless of the number of users who use that device to access the server. Device CALs may make more economic and administrative sense if your company has workers who share devices, for example, on different work shifts. 


A SharePoint Server device CAL authorizes one computer to access SharePoint Server, regardless of the number of users (for example, a shared workstation).

SharePoint Server User CALs are also available. A user CAL authorizes a user to access SharePoint Server from any device (for example, when an employee accesses the server from a computer at work and another at home). 

Client Access License based on device

External Connectors

If you want external users—such as business partners, external contractors, or customers—to be able to access your network, you have two licensing options:
·         Acquire CALs for each of your external users.
·         Acquire External Connector (EC) licenses for each server that will be accessed by your external users.
For SharePoint, Acquire External Connector (EC) licenses would be the right choice.

External Connector licensing

Specialty Server Licensing

Specialty Server licensing is a commonly used model. Specialty Servers are server-only licenses that also do not require CALs. Specialty Servers require a server license for each instance of the server software running on a server. An example of this is Microsoft Office SharePoint Server for Internet Sites. You can run the instance in a physical or virtual operating system environment. By exception, some products provide more specific use rights.
 Specialty Server licensing

Thursday, February 28, 2013

Sync list with user group using jquery

Requirement: To get all the user names from the SharePoint group "Deliverable Owners" and sync with a custom list called "Team Members" in a button click.

Solution: This is done using jquery and SharePoint web services.

Code:

<script type="text/javascript" src="https://siteurl/Documents/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="https://siteurl/Documents/jquery.SPServices-0.7.2.min.js"></script>
<script  type="text/javascript">
    $(document).ready(function() {
 
     $("#syncUsers").click(function()  //'syncUsers' is the ID of button control added in the CEWP
{
var errorOccured  = DeleteUsersFromTeamMembersList();
if(!errorOccured)
{
AddUsersToTeamMembersList();
}
 });
});

      // to delete the existing users from the custom list
function DeleteUsersFromTeamMembersList()
{

var errorOccured = false;

$().SPServices({
            operation: "GetListItems",
            async: false,
            debug: true,
            listName: "Team Members",
            CAMLViewFields: "<ViewFields></ViewFields>",
            completefunc: function (xData, Status) {
                $(xData.responseXML).SPFilterNode("z:row").each(function() {
                    $().SPServices({
                        operation: "UpdateListItems",
                        async: false,
                        debug: true,
                        batchCmd: "Delete",
                        listName: "Team Members",
                        ID: $(this).attr("ows_ID"),
                        completefunc: function (xData, Status) {
                        msgData = xData.responseText;
isError = msgData.indexOf("ErrorText");
           if (isError > 0) {
               // Error creating fields!
               alert("Error deleted user names from Team Member list!");
               errorOccured = true;
           }
                        }
                    });
                });
            }
        });
         return errorOccured;
}
//add all the users from the sharepoint group to custom list.
function AddUsersToTeamMembersList()
{

var alreadyProcessed = false;
var userName ;
var iD;
var userID;
var errorOccured = false;

$().SPServices({
operation: "GetUserCollectionFromGroup",
groupName: "Deliverable Owners",
completefunc: function (xData, Status) {
$("#results").text(xData.responseXML.xml);
$(xData.responseXML).find("User").each(function () {
  userName = $(this).attr("LoginName");
  iD = $(this).attr("ID");
  userID = iD +";#"+userName;
  $().SPServices({
operation: "UpdateListItems",
async: false,
batchCmd: "New",
listName: "Team Members",
valuepairs: [["User",userID  ]],
completefunc: function(xData, Status)
{
msgData = xData.responseText;
isError = msgData.indexOf("ErrorText");
if (isError > 0) {
// Error creating fields!
alert("Error synchronizing user names!");
errorOccured = true;
}
}
});
});

if( errorOccured == false)
{
alert("User name synchronized successfully.");
$(window.location).attr('href', 'currentpagename.aspx');
}                    
}
});
}
</script>


P.S:
- The performance of this code will get affected based on the size of the user group.
- The Team Members custom list must have "User" field with people and group type.